Java调用第三方API
示例代码:
private final static String CONTENT_TYPE = "application/json";
private final static String CHARSET = "UTF-8";
private final static String EN_CONING = "UTF-8";
public static void httpRequest(String requestUrl, Object params) throws IOException {
String result = "";
CloseableHttpClient client = HttpClientBuilder.create().build();
CloseableHttpResponse response = null;
try {
//设post请求
HttpPost post = new HttpPost(requestUrl);
//创建请求实体传参
StringEntity postingString = new StringEntity(JSONObject.toJSONString(params),CHARSET);
postingString.setContentEncoding(EN_CONING);
//设置post请求参数
post.setEntity(postingString);
post.addHeader(HTTP.CONTENT_TYPE,CONTENT_TYPE);
//执行post请求
response = client.execute(post);
//访问成功状态码为200
System.out.println(response);
if (response.getStatusLine().getStatusCode() == 200) {
//从响应中获取实体内容,通过EntityUtils(工具)转成字符串
result = EntityUtils.toString(response.getEntity());
//响应内容中文会乱码,需要转json对象
JSONObject jsonObject = JSONObject.parseObject(result);
System.out.println(jsonObject);
} else {
System.out.println("出错!");
}
} catch (IOException e) {
e.printStackTrace();
}finally {
client.close();
response.close();
}
}
出现415错误的解决方法:
- 前端看ajax请求的content Type是否与后端一致
- 看发送的数据格式是否正确。
出现 Illegal character in path at index 56报错信息:
检查请求链接是否有误,是否存在空格。