Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
Projects A and B are deployed on a different host, or deployed in a host of different ports of the same, involving cross-domain access between AB.
A required response data B, and B data format is not want A, can now be achieved using HttpClient cross-domain access, format conversion and the number of completed java code.
Add dependent
<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();
}
}
}
}