写代码的时候 ,需要使用 http post 提交表单 获取相关数据解析、
但是 我通过 java 编写 模拟浏览器 提交表单数据,发现 获取不了数据。
设置了各种参数都不行,无奈 百度了几下。看到了一行代码使我眼前一亮,顺利解决了我的问题。特此分享出来、希望能够帮助还没解决类似问题的程序猿参考下 。具体谁写的不记得了,只拷贝了代码部分。
/**
* httpclient模拟post请求json封装表单数据
* @param url
* @param json
* @return
* @throws Exception
*/
public static String httpPostWithJSON(String url,String json) throws Exception {
HttpPost httpPost = new HttpPost(url);
CloseableHttpClient client = HttpClients.createDefault();
String respContent = null;
// json方式
StringEntity entity = new StringEntity(json,"utf-8");//解决中文乱码问题
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
System.out.println();
// 表单方式
// 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"));
HttpResponse resp = client.execute(httpPost);
if(resp.getStatusLine().getStatusCode() == 200) {
HttpEntity he = resp.getEntity();
respContent = EntityUtils.toString(he,"UTF-8");
}
return respContent;
}