使用java的HttpClient调用远程接口
httpClient比jdk自带的URLConection更加易用和方便,这里介绍一下使用httpClient来调用远程接口。
首先导入相关的依赖包:
<!-- httpClient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.3</version> </dependency>
使用方法:
1,创建HttpClient对象;
2,指定请求URL,并创建请求对象,如果是get请求则创建HttpGet对象,post则创建HttpPost对象;
3,如果请求带有参数,对于get请求可直接在URL中加上参数请求,或者使用setParam(HetpParams params)方法设置参数,对于HttpPost请求,可使用setParam(HetpParams params)方法或者调用setEntity(HttpEntity entity)方法设置参数;
4,调用httpClient的execute(HttpUriRequest request)执行请求,返回结果是一个response对象;
5,通过response的getHeaders(String name)或getAllHeaders()可获得请求头部信息,getEntity()方法获取HttpEntity对象,该对象包装了服务器的响应内容。
实例:
博主使用了property文件来保存不同API对应的链接,也可以除去properties文件的读取代码,直接将变量 API换成所需URL
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
import java.util.Properties;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class APIUtil {
/**
* 返回API调用结果
* @param APIName 接口在api.properties中的名称
* @param params 访问api所需的参数及参数值
* @return 此处返回的是JSON格式的数据
*/
public static String API(String APIName, Map<String, Object> params) {
String content = "";
//请求结果
CloseableHttpResponse response = null;
//实例化httpclient
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
//读取配置文件的URL
Properties properties = new Properties();
URL fileURL = APIUtil.class.getClassLoader().getResource("api.properties");
properties.load(new FileInputStream(new File(fileURL.getFile())));
String API = properties.getProperty(APIName);
//构造url请求
StringBuilder url = new StringBuilder(API);
if(params!=null && params.size()>0) {
url.append("?");
for(Map.Entry<String, Object> entry : params.entrySet()) {
url.append(entry.getKey()+"="+entry.getValue()+"&");
}
url.substring(0, url.length()-1);
}
//实例化get方法
HttpGet httpget = new HttpGet(url.toString());
//执行get请求
response = httpclient.execute(httpget);
if(response.getStatusLine().getStatusCode()==200) {
content = EntityUtils.toString(response.getEntity(),"utf-8");
}
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
}
执行完毕后返回API提供的数据。
有意见或疑问欢迎提出来
