项目A和项目B部署在不同的主机上,或者部署在同一个主机的不同端口下,AB之间的访问涉及跨域。
A需要B响应数据,而B的数据格式不是A想要的,此时可以使用HttpClient实现跨域访问,并且用java代码完成数格式转换。
添加依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.5</version>
</dependency>
demo
package com.clc.test;
import java.io.IOException;
import java.net.URI;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientTest {
public static void main(String[] args) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
try {
//创建请求地址
URI uri = new URIBuilder("https://www.baidu.com/s").setParameter("wd", "csdn").build();
HttpGet httpGet = new HttpGet(uri);
//HttpGet httpGet = new HttpGet("https://www.baidu.com/s?wd=csdn");
//发送请求,接收响应数据
response = httpClient.execute(httpGet);
//获取状态码
System.out.println(response.getStatusLine().getStatusCode());
//获取响应数据
String content = EntityUtils.toString(response.getEntity(),"utf-8");
System.out.println(content);
} catch (Exception e) {
e.printStackTrace();
}finally {
//关闭资源
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
}
}
}