public static String httpRequestToString(String url, String requestMethod,String param){
String methodResult = null;
try {
boolean isGet = "get".equalsIgnoreCase(requestMethod);
boolean isPost = "post".equalsIgnoreCase(requestMethod);
boolean isPut = "put".equalsIgnoreCase(requestMethod);
boolean isDelete = "delete".equalsIgnoreCase(requestMethod);
CloseableHttpClient client = HttpClients.createDefault();
HttpRequestBase method = null;
if(isGet){
method = new HttpGet(url);
}else if(isPost){
method = new HttpPost(url);
HttpPost postMethod = (HttpPost) method;
StringEntity entity = new StringEntity(param);
postMethod.setEntity(entity);
}else if(isPut){
method = new HttpPut(url);
HttpPut putMethod = (HttpPut) method;
}else if(isDelete){
method = new HttpDelete(url);
}
method.addHeader("Content-Type","application/x-www-form-urlencoded");
HttpClientContext context = HttpClientContext.create(); // 请求上下文,博客中有介绍
HttpResponse response = client.execute(method);
if(response.getStatusLine().getStatusCode()==200){
methodResult = EntityUtils.toString(response.getEntity());
}
client.close();
}catch (UnsupportedEncodingException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
return methodResult;
}
构建请求参数
JsonObject requesrObj=new JsonObject();
requesrObj.addProperty("token", "");
requesrObj.addProperty("version", "2.1");
requesrObj.addProperty("userId", "1");
requesrObj.addProperty("appDeviceNumber", "EFO4775544744444584JK");
requesrObj.addProperty("platform", "0");
//----------------------------------------------以上请求包不动
//----------------------------------------------一下为param里面得参数
JsonObject paramObj=new JsonObject();
paramObj.addProperty("objId", "06e878ad-8336-488f-a3fc-501b5a088bfd");
requesrObj.add("param", paramObj);
System.out.println(requesrObj.toString());