开发中遇到服务间通过restful接口进行远程调用的情况,可以使用如下的方式进行实现:
maven依赖如下:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
代码实现如下:
package com.shencai.xf.common.util;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
/**
* @Description: 描述
* @Author: xuyahui
* @Date: 2019/8/13 17:17
* @Version 1.0
*/
public class HttpUtil {
private static Logger logger = LoggerFactory.getLogger(HttpUtil.class.getName());
private static HttpClient httpClient = HttpClientBuilder.create().build();
public static String httpPost(String url, String json) {
HttpPost post = new HttpPost(url);
post.addHeader(HTTP.CONTENT_TYPE, "application/json");
StringEntity entity = new StringEntity(json, "UTF-8");
post.setEntity(entity);
try {
HttpResponse response = httpClient.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
if (response.getEntity() != null) {
return EntityUtils.toString(response.getEntity(), "UTF-8");
}
}
throw new IOException("请求出错");
} catch (IOException e) {
e.printStackTrace();
logger.error(e.getMessage());
}
return null;
}
public static JSONObject httpGet(String url){
JSONObject jsonObject = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet get = new HttpGet(url);
try {
HttpResponse response = httpClient.execute(get);
HttpEntity entity = response.getEntity();
String returnString= EntityUtils.toString(entity, "UTF-8");
EntityUtils.consume(entity);
jsonObject = JSONObject.parseObject(returnString);
} catch (IOException e) {
LOG.error("http请求失败", e);
}
return jsonObject;
}
}