一 . 概述
跨服务器请求数据方式有很多种,本文介绍 OKHttp3 与 httpclient 两种方式,两种方式返回的数据格式是json, json解析请参考https://www.jianshu.com/writer#/notebooks/39950651/notes/54439484/preview
二 . OKHttp3
2.1 步骤一 : 导包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--okhttp3-->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.2.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.60</version>
</dependency>
2.2 步骤二 : 配置 spring-config(设定超时)
@Bean
public OkHttpClient okHttpClient() {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30,TimeUnit.SECONDS)
.retryOnConnectionFailure(true);
return builder.build();
}
2.3 步骤三: 在controller层 的get请求
@RestController
@RequestMapping("/test")
public String run(String url) throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
注:这样是原封不动把JSON数据返回给前端
附 post请求
public static final MediaType JSON
= MediaType.get("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
三 . Httpclient
3.1 步骤一导包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.60</version>
</dependency>
3.2 步骤二 : 编写工具类HttpProtocolHandler
public class HttpProtocolHandler {
/**
* 请求方式
*/
public enum Request_method {
POST, GET
}
/**
* Http连接管理器,该管理器必须是线程安全的
*/
private static PoolingHttpClientConnectionManager connectionManager;
/**
* 最大的连接数量
*/
private int maxTotal = 100;
/**
* 每个路径最大的连接数
*/
private int maxConnPerRoute = 20;
private static HttpProtocolHandler httpProtocolHandler = new HttpProtocolHandler();
public HttpProtocolHandler() {
/**
* Http连接池
*/
connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(maxTotal);
connectionManager.setDefaultMaxPerRoute(maxConnPerRoute);
}
public static HttpProtocolHandler getInstance() {
return httpProtocolHandler;
}
// 具体的调用方法
public String execute(Request_method requestMethod, String url, Map<String, String> paramsMap) {
String responseStr = null;
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();
List<NameValuePair> nameValuePair = generatNameValuePair(paramsMap);
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePair, Consts.UTF_8);
HttpUriRequest uriRequest = Request_method.GET.equals(requestMethod) ? new HttpGet(generatRequestUrl(url, paramsMap)) : new HttpPost(url);
if (Request_method.POST.equals(requestMethod)) {
((HttpPost) uriRequest).setEntity(entity);
}
try {
HttpResponse httpResponse = httpClient.execute(uriRequest);
responseStr = EntityUtils.toString(httpResponse.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
/**
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
*/
}
return responseStr;
}
/**
* POST请求参数的组装
*/
public static List<NameValuePair> generatNameValuePair(Map<String, String> paramsMap) {
List<NameValuePair> nameValuePair = new LinkedList<NameValuePair>();
for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
nameValuePair.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
return nameValuePair;
}
/**
* GET请求的参数的封装
*
* @param url
* @param paramsMap
* @return
*/
public static String generatRequestUrl(String url, Map<String, String> paramsMap) {
StringBuffer fullUrl = new StringBuffer(url);
if (paramsMap != null && paramsMap.size() > 0) {
fullUrl.append("?");
int i = 0;
for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
i++;
String paramName = entry.getKey();
String paramValue = entry.getValue();
fullUrl.append(i == paramsMap.size() ? paramName + "=" + paramValue : paramName + "=" + paramValue + "&");
}
}
return fullUrl.toString();
}
}
3.3 在controller层调用
@RestController
@RequestMapping("/remote")
public class RemoteController {
private HttpProtocolHandler handler = new HttpProtocolHandler();
@RequestMapping
public Object getUser() {
String url = "http://localhost:8080/user";
Map<String, String> map = new HashMap<>();
String result = handler.execute(HttpProtocolHandler.Request_method.GET, url, map);
return result;
}
}
网友评论