在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 }
以上接口已给出具体的注释,可以根据接口的具体情况进行修改。