java中如何使用HttpClient调用接口

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

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

标签:java,HttpClient,调用接口
0
投稿

猜你喜欢

  • maven多profile 打包下 -P参和-D参数的实现

    2023-03-22 08:25:08
  • Java 常见排序算法代码分享

    2023-09-30 08:23:09
  • Mybatis插件之自动生成不使用默认的驼峰式操作

    2023-11-19 01:20:03
  • Maven工程打包jar的多种方式

    2022-12-15 06:54:46
  • C# Newtonsoft.Json 解析多嵌套json 进行反序列化的实例

    2022-04-09 11:23:13
  • ReentrantLock获取锁释放锁的流程示例分析

    2021-08-05 20:51:10
  • Spring源码解密之自定义标签与解析

    2023-11-25 01:11:34
  • 基于Java实现的图的广度优先遍历算法

    2021-06-02 06:51:20
  • Java设计模式之模板方法模式Template Method Pattern详解

    2023-09-21 12:28:04
  • C#模拟实现QQ窗体功能

    2021-07-17 02:49:11
  • Java实现双向循环链表

    2023-11-08 04:14:40
  • Android中通过RxJava进行响应式程序设计的入门指南

    2023-06-27 08:17:46
  • Spring IOC与DI核心重点分析

    2023-11-12 14:35:55
  • 使用Java的Lucene搜索工具对检索结果进行分组和分页

    2022-07-27 05:21:17
  • swing分割窗口控件JSplitPane使用方法详解

    2021-07-28 14:15:20
  • SpringBoot封装JDBC的实现步骤

    2022-09-13 04:04:31
  • Spring4下validation数据校验无效(maven)的解决

    2022-01-24 03:01:04
  • MyBatis利用MyCat实现多租户的简单思路分享

    2022-08-16 18:58:33
  • Java 栈与队列超详细分析讲解

    2023-08-15 01:09:07
  • Springboot2.x+ShardingSphere实现分库分表的示例代码

    2023-11-26 01:34:07
  • asp之家 软件编程 m.aspxhome.com