java 測試post請求 在body里面傳遞參數怎么設置,怎么接收
問題描述
public String post(String strURL,String params) {
System.out.println(strURL); System.out.println(params); try {URL url = new URL(strURL);//創建連接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestMethod('POST');//設置請求方式 connection.setRequestProperty('Accept','application/json');//設置接收數據的格式 connection.setRequestProperty('Content-Type','application/json');//設置發送數據的格式 connection.connect(); OutputStreamWriter out = new OutputStreamWriter( connection.getOutputStream(),'UTF-8');// utf-8編碼 out.append(params); out.flush(); out.close(); //讀取響應 int length = (int) connection.getContentLength();//獲取長度 InputStream is = connection.getInputStream(); if (length != -1){ byte[] data = new byte[length]; byte[] temp = new byte[512]; int readLen = 0; int destPos = 0; while ((readLen = is.read(temp)) > 0){System.arraycopy(temp, 0, data, destPos, readLen); destPos += readLen; } String result = new String(data, 'UTF-8'); System.out.println(result); return result; } } catch (Exception e) {// TODO: handle exceptione.printStackTrace(); } return 'error'; }
@RequestMapping(value='/text', method = RequestMethod.POST)@ResponseBodypublic String text(HttpServletRequest request,HttpServletResponse response,@RequestBody String t){ System.out.println(t); return 'DetailedRules';}
問題解答
回答1:你可以用Paw或者Insomnia或者ARC來測試,不用寫代碼啦
回答2:conn.setParam設置參數值。。。下個fiddler,調試快
回答3:如果只是測試接口,chorme里面下個postman測試就好了
相關文章:
