java post请求的表单提交和json提交简单小结

时间:2023-03-10 03:15:24
java post请求的表单提交和json提交简单小结

在java实现http请求时有分为多种参数的传递方式,以下给出通过form表单提交和json提交的参数传递方式:

 public String POST_FORM(String url, Map<String,String> map,String encoding) throws ParseException, IOException{
String body = "";
//创建httpclient对象
CloseableHttpClient client = HttpClients.createDefault();
//创建post方式请求对象
HttpPost httpPost = new HttpPost(url); List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
if(map!=null){
for (Entry<String, String> entry : map.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
//设置参数到请求对象中
httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding)); //设置连接超时时间 为3秒
RequestConfig config = RequestConfig.custom().setConnectTimeout(3000).setConnectionRequestTimeout(3000).setSocketTimeout(5000).build();
httpPost.setConfig(config);
System.out.println("请求地址:"+url);
System.out.println("请求参数:"+nvps.toString()); //1.表单方式提交数据 简单举例,上面给出的是map参数
// List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
// pairList.add(new BasicNameValuePair("name", "admin"));
// pairList.add(new BasicNameValuePair("pass", "123456"));
// httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8")); //2.json方式传值提交
// JSONObject jsonParam = new JSONObject();
// jsonParam.put("name", "admin");
// jsonParam.put("pass", "123456");
// StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");// 解决中文乱码问题
// entity.setContentEncoding("UTF-8");
// entity.setContentType("application/json");
// httpPost.setEntity(entity); //可以设置header信息 此方法不设置
//指定报文头【Content-type】、【User-Agent】
// httpPost.setHeader("Content-type", "application/json");
// httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //执行请求操作,并拿到结果(同步阻塞)
CloseableHttpResponse response = client.execute(httpPost);
//获取结果实体
HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, encoding);
}
EntityUtils.consume(entity);
//释放链接
response.close();
return body;
}

以上接口已给出具体的注释,可以根据接口的具体情况进行修改。