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     }

以上接口已給出具體的注釋,可以根據接口的具體情況進行修改。

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM