1、数据交互方式:http;
2、使用技术【引入jar依赖】
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
3、java代码
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
/**
* httpClient工具类
*/
public class HttpClientUtil {
/**
* Post请求方法
*
* @param uri 请求地址
* @param content 发送内容
* @return
*/
public static String doPost(String uri, String content) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(uri);
post.addHeader("Accept", "application/json");
post.addHeader("Content-Type", "application/json");
StringEntity reqEntity = new StringEntity(content, "utf-8");
reqEntity.setContentEncoding("UTF-8");
reqEntity.setContentType("application/json");
post.setEntity(reqEntity); // 设置请求的数据
try {
HttpResponse resp = client.execute(post);
HttpEntity httpEntity = resp.getEntity();
return EntityUtils.toString(httpEntity, "UTF-8").trim();
} catch (Exception e) {
return e.getMessage();
}
}
/**
* 发送get请求
* @param uri 请求地址
* @return
*/
public static String doGet(String uri) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(uri);
httpGet.setHeader("User-Agent", "Mozilla/5.0");
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
HttpEntity httpEntity = response.getEntity();
return EntityUtils.toString(httpEntity, "UTF-8").trim();
} catch (IOException e) {
return e.getMessage();
}
}
}