1. 程式人生 > >java post請求的表單提交和json提交簡單小結

java post請求的表單提交和json提交簡單小結

在java實現http請求時有分為多種引數的傳遞方式,以下給出通過form表單提交和json提交的引數傳遞方式:

 1 public String POST_FORM(String url, Map<String,String> map,String encoding) throws ParseException, IOException{  
 2         String body = "";  
 3         //建立httpclient物件  
 4         CloseableHttpClient client = HttpClients.createDefault();  
5 //建立post方式請求物件 6 HttpPost httpPost = new HttpPost(url); 7 8 List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>(); 9 if(map!=null){ 10 for (Entry<String, String> entry : map.entrySet()) { 11 nvps.add(new
BasicNameValuePair(entry.getKey(), entry.getValue())); 12 } 13 } 14 //設定引數到請求物件中 15 httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding)); 16 17 //設定連線超時時間 為3秒 18 RequestConfig config = RequestConfig.custom().setConnectTimeout(3000).setConnectionRequestTimeout(3000).setSocketTimeout(5000).build();
19 httpPost.setConfig(config); 20 System.out.println("請求地址:"+url); 21 System.out.println("請求引數:"+nvps.toString()); 22 23 //1.表單方式提交資料 簡單舉例,上面給出的是map引數 24 // List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>(); 25 // pairList.add(new BasicNameValuePair("name", "admin")); 26 // pairList.add(new BasicNameValuePair("pass", "123456")); 27 // httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8")); 28 29 //2.json方式傳值提交 30 // JSONObject jsonParam = new JSONObject(); 31 // jsonParam.put("name", "admin"); 32 // jsonParam.put("pass", "123456"); 33 // StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");// 解決中文亂碼問題 34 // entity.setContentEncoding("UTF-8"); 35 // entity.setContentType("application/json"); 36 // httpPost.setEntity(entity); 37 38 //可以設定header資訊 此方法不設定 39 //指定報文頭【Content-type】、【User-Agent】 40 // httpPost.setHeader("Content-type", "application/json"); 41 // httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); 42 43 //執行請求操作,並拿到結果(同步阻塞) 44 CloseableHttpResponse response = client.execute(httpPost); 45 //獲取結果實體 46 HttpEntity entity = response.getEntity(); 47 if (entity != null) { 48 //按指定編碼轉換結果實體為String型別 49 body = EntityUtils.toString(entity, encoding); 50 } 51 EntityUtils.consume(entity); 52 //釋放連結 53 response.close(); 54 return body; 55 }

以上介面已給出具體的註釋,可以根據介面的具體情況進行修改。