Java模拟HTTP/POST方式请求接口:
java模拟http/post方式请求接口方法主体:
public String sendPost(JSONObject json, String url){
String result = "";
HttpPost post = new HttpPost(url);
try{
CloseableHttpClient httpClient = HttpClients.createDefault();
post.setHeader("Content-Type","application/json;charset=utf-8");
post.addHeader("Authorization", "Basic YWRtaW46");
StringEntity postingString = new StringEntity(json.toString(),"utf-8");
post.setEntity(postingString);
HttpResponse response = httpClient.execute(post);
InputStream in = response.getEntity().getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
StringBuilder strber= new StringBuilder();
String line = null;
while((line = br.readLine())!=null){
strber.append(line+'\n');
}
br.close();
in.close();
result = strber.toString();
if(response.getStatusLine().getStatusCode()!= HttpStatus.SC_OK){
result = "服务器异常";
}
} catch (Exception e){
System.out.println("请求异常");
throw new RuntimeException(e);
} finally{
post.abort();
}
return result;
}
接口调用方法:
public String sendPostTest() {
JSONObject jsonObject = new JSONObject();
//添加参数,参数为JSON格式
jsonObject.put("namecode", "zhouxf4110");
String url = "http://localhost/***/userMassage/queryUserByList";
//调用接口,返回字符串,返回值自行处理
String str = sendPost(jsonObject, url);
System.out.println(str);
return str;
}
pom文件配置:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>