软件编程
位置:首页>> 软件编程>> java编程>> java中如何使用HttpClient调用接口

java中如何使用HttpClient调用接口

作者:蚕豆是个程序猿  发布时间:2021-10-13 11:19:14 

标签:java,HttpClient,调用接口

java使用HttpClient调用接口

HttpClient 提供的主要的功能

(1)实现了所有 HTTP 的方法(GET,POST,PUT,DELETE 等)

(2)支持自动转向

(3)支持 HTTPS 协议

(4)支持代理服务器等

直接言归正传了!!!!上代码

public static String sendPutForm(String url,  Map<String,String> map, String encoding) throws ParseException, IOException {
       String body = "";
       // 打印了一下我推送的json数据
       log.info("我推送的json数据:" + map);
       log.info("我推送的url:" + url);
       CloseableHttpResponse response = null;
       ///获得Http客户端
       CloseableHttpClient client = HttpClients.createDefault();
       List<NameValuePair> parameters = new ArrayList<NameValuePair>();
       for (Map.Entry<String, String> entry : map.entrySet()) {
           System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue());
           parameters.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
       }
       UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
// 配置信息
// 设置连接超时时间(单位毫秒)
// 设置请求超时时间(单位毫秒)
// socket读写超时时间(单位毫秒)
       RequestConfig requestConfig = RequestConfig.custom()
               .setConnectTimeout(50000).setConnectionRequestTimeout(50000)
               .setSocketTimeout(50000).build();
       // 向指定资源位置上传内容// 创建Post请求
       HttpPost httpPost = new HttpPost(url);
       httpPost.setConfig(requestConfig);
       httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
       httpPost.setEntity(formEntity);
       try {
           response = client.execute(httpPost);
           // 通过response中的getEntity()方法获取返回值
           HttpEntity entity = response.getEntity();
           if (entity != null) {
               body = EntityUtils.toString(entity, encoding);
           }
       } catch (Exception e) {
           // TODO: handle exception
           e.printStackTrace();
       } finally {
           httpPost.abort();
           if (response != null) {
               EntityUtils.consumeQuietly(response.getEntity());
           }
       }
       log.info("body:" + body);
       return body;
   }

代码其实就是这么多,还有好多形式。大家可以参考写一下。

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提供的数据。

来源:https://blog.csdn.net/m0_46379371/article/details/108983897

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com