JAVA实现http接口调用
Get请求
Get请求比较简单,代码如下:
/**
* 返回API调用结果
*
* @param APIName 接口在api.properties中的名称
* @param params 访问api所需的参数及参数值
* @return 此处返回的是JSON格式的数据
*/
public static String linkUrl(String uri, String APIName, Map<String, String> params) {
String content = "";
//请求结果
CloseableHttpResponse response = null;
//实例化httpclient
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
//http://192.168.1.107/user/list
String api = generateUrl(uri,APIName);
//构造url请求
if (params != null && params.size() > 0) {
api += "?";
for (Map.Entry<String, String> entry : params.entrySet()) {
api += entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), encoding) + "&";
}
api = api.substring(0, api.length() - 1);
}
//实例化get方法
HttpGet httpget = new HttpGet(api);
//执行get请求
response = httpclient.execute(httpget);
if (response.getStatusLine().getStatusCode() == 200) {
content = EntityUtils.toString(response.getEntity(), encoding);
}
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
POST请求
- 参数为表单格式
/**
*功能描述
* @Title
* @description : post请求
* @author yanbo
* @create 2019/5/9 12:20
* @param * @param: url
* @param: map
* @param: encoding
* @return java.lang.String
*/
public static String sendPost(String uri, String APIName,Map<String, String> map) throws ParseException, IOException {
String body = "";
//http://192.168.1.107/user/list
String url = generateUrl(uri,APIName);
//创建httpclient对象
CloseableHttpClient client = HttpClients.createDefault();
//创建post方式请求对象
HttpPost httpPost = new HttpPost(url);
//装填参数
List<NameValuePair> nvps = new ArrayList<>();
if (map != null) {
for (Map.Entry<String, String> entry : map.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
//设置参数到请求对象中
httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));
// System.out.println("请求地址:" + url);
// System.out.println("请求参数:" + nvps.toString());
//设置header信息
//指定报文头【Content-type】、【User-Agent】
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//执行请求操作,并拿到结果(同步阻塞)
CloseableHttpResponse response = client.execute(httpPost);
//获取结果实体
HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, encoding);
}
EntityUtils.consume(entity);
//释放链接
response.close();
return body;
}
- 参数为json格式
public static JSONObject doPost(String url, String json) {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
JSONObject response = null;
try {
StringEntity s = new StringEntity(json);
s.setContentEncoding("UTF-8");
//发送json数据需要设置contentType
s.setContentType("application/json");
post.setEntity(s);
HttpResponse res = client.execute(post);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = res.getEntity();
// 返回json格式:
String result = EntityUtils.toString(entity,"UTF-8");
response = JSONObject.fromObject(result);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return response;
}
上面的代码用的 HttpEntity是 StringEntity
, 如果你要请求的接口没有给你指定,而且返回结果和你用postman等工具测试结果返回不一样,那么可能是这个entity的编码有问题了,可以设置编码,
new StringEntityURLEncoder.encode(JSON.toJSONString(requestMap), "UTF-8"))
如果编码没问题了,但是对方那里判断的结果,和你参数应该正常的判断结果不一致,也有可能是序列化协议不匹配,建议试一试下面的方式:
ByteArrayEntity entity = null;
entity = new ByteArrayEntity(requestBody.getBytes("UTF-8"));
entity.setContentType("application/json");
httpPost.setEntity(entity);
如果请求的是 https,报什么 javax.net.ssl.SSLException: Certificate for <msgo.10010.com> doesn't match any of the subject alternative names
这种错误,那么需要你的HTTPClient要这样写:
SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(
SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(), NoopHostnameVerifier.INSTANCE);
CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(scsf).build();