java后台模拟页面post请求
/**
*targetUrl:请求url
*urlParam:需要封装进url的参数
*body:需要传递的参数
*type:请求格式类型:1.json;2.form-data;3.x-www-form-urlencoded
*/
private String httpPOST(String targetUrl,JSONObject urlParamJosn,JSONObject body,int type){
try{
CloseableHttpClient httpClient = HttpClients.createDefault();
StringBuilder param=new StringBuilder("");
for (String key:urlParamJosn.keySet()){
param.append(key + "=" + URLEncoder.encode((String) urlParamJosn.get(key), "UTF-8") + "&");
}
String targetUrl = targetUrl+(param.indexOf("&") > 0?param.deleteCharAt(param.lastIndexOf("&")).toString():"");
HttpPost httpPost = new HttpPost(targetUrl);
if(body != null && !body.isEmpty()){
if (type == 1) {
StringEntity entity=new StringEntity(body.toJSONString(), ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
}else if (type == 2) {
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
for (String key:body.keySet()){
multipartEntityBuilder.addPart(key, new StringBody(body.get(key).toString(), ContentType.create("text/plain", Consts.UTF_8)));
}
httpPost.setEntity(multipartEntityBuilder.build());
}else if (type == 3) {
List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
for (String key:body.keySet()){
params.add(new BasicNameValuePair(key, body.get(key).toString()));
}
HttpEntity reqEntity = new UrlEncodedFormEntity(params);
System.out.println("the request body is:"+EntityUtils.toString(reqEntity));
httpPost.setEntity(reqEntity);
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
}
}
HttpResponse result = httpClient.execute(httpPost);
System.out.println(result.getStatusLine().getStatusCode());
if (302 == result.getStatusLine().getStatusCode()) {
System.out.println(result.getFirstHeader("location"));
return result.getFirstHeader("location").getValue();
}
HttpEntity entity = result.getEntity();
return EntityUtils.toString(entity, "UTF-8");
}catch(Exception e){
e.printStackTrace();
}
return null;
}
- json类型用StringEntity实例。 form-data类型用multipartEntity 实例。
x-www-form-urlencoded类型用UrlEncodedFormEntity实例。