您现在的位置是:首页 > 编程语言学习 > 其他编程语言 > 文章正文 其他编程语言

java中如何使用HttpClient调用接口

2022-10-27 10:05:40 其他编程语言

简介这篇文章主要介绍了java中如何使用HttpClient调用接口,具有很好的参考价值,希望对大家有所帮助。java使用HttpClient调用接口HttpClient ...

这篇文章主要介绍了java中如何使用HttpClient调用接口,具有很好的参考价值,希望对大家有所帮助。

java使用HttpClient调用接口

HttpClient 提供的主要的功能

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

(2)支持自动转向

(3)支持 HTTPS 协议

(4)支持代理服务器等

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

  1.  public static String sendPutForm(String url,  Map map, String encoding) throws ParseException, IOException { 
  2. String body = ""
  3. // 打印了一下我推送的json数据 
  4. log.info("我推送的json数据:" + map); 
  5. log.info("我推送的url:" + url); 
  6. CloseableHttpResponse response = null
  7. ///获得Http客户端 
  8. CloseableHttpClient client = HttpClients.createDefault(); 
  9. List parameters = new ArrayList(); 
  10. for (Map.Entry entry : map.entrySet()) { 
  11. System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue()); 
  12. parameters.add(new BasicNameValuePair(entry.getKey(),entry.getValue())); 
  13. UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters); 
  14.         // 配置信息 
  15.         // 设置连接超时时间(单位毫秒) 
  16.         // 设置请求超时时间(单位毫秒) 
  17.         // socket读写超时时间(单位毫秒) 
  18. RequestConfig requestConfig = RequestConfig.custom() 
  19. .setConnectTimeout(50000).setConnectionRequestTimeout(50000) 
  20. .setSocketTimeout(50000).build(); 
  21. // 向指定资源位置上传内容// 创建Post请求 
  22. HttpPost httpPost = new HttpPost(url); 
  23. httpPost.setConfig(requestConfig); 
  24. httpPost.addHeader("Content-Type""application/x-www-form-urlencoded;charset=utf-8"); 
  25. httpPost.setEntity(formEntity); 
  26. try { 
  27. response = client.execute(httpPost); 
  28. // 通过response中的getEntity()方法获取返回值 
  29. HttpEntity entity = response.getEntity(); 
  30. if (entity != null) { 
  31. body = EntityUtils.toString(entity, encoding); 
  32. catch (Exception e) { 
  33. // TODO: handle exception 
  34. e.printStackTrace(); 
  35. finally { 
  36. httpPost.abort(); 
  37. if (response != null) { 
  38. EntityUtils.consumeQuietly(response.getEntity()); 
  39. log.info("body:" + body); 
  40. return body; 

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

java的HttpClient调用远程接口

httpClient比jdk自带的URLConection更加易用和方便,这里介绍一下使用httpClient来调用远程接口。

首先导入相关的依赖包:

  1. <!-- httpClient --> 
  2.         <dependency> 
  3.             <groupId>org.apache.httpcomponents</groupId> 
  4.             <artifactId>httpclient</artifactId> 
  5.             <version>4.5.3</version> 
  6.         </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

  1. import java.io.File; 
  2. import java.io.FileInputStream; 
  3. import java.io.IOException; 
  4. import java.net.URL; 
  5. import java.util.Map; 
  6. import java.util.Properties; 
  7.   
  8. import org.apache.http.client.methods.CloseableHttpResponse; 
  9. import org.apache.http.client.methods.HttpGet; 
  10. import org.apache.http.impl.client.CloseableHttpClient; 
  11. import org.apache.http.impl.client.HttpClients; 
  12. import org.apache.http.util.EntityUtils; 
  13.   
  14. public class APIUtil { 
  15.   
  16.     /** 
  17.      * 返回API调用结果 
  18.      * @param APIName 接口在api.properties中的名称 
  19.      * @param params 访问api所需的参数及参数值 
  20.      * @return 此处返回的是JSON格式的数据 
  21.      */ 
  22.     public static String API(String APIName, Map params) { 
  23.          String content = ""
  24.          //请求结果   
  25. CloseableHttpResponse response = null;   
  26.         //实例化httpclient   
  27. CloseableHttpClient httpclient = HttpClients.createDefault();   
  28.     
  29. try { 
  30.      //读取配置文件的URL 
  31. Properties properties = new Properties(); 
  32. URL fileURL = APIUtil.class.getClassLoader().getResource("api.properties"); 
  33.         properties.load(new FileInputStream(new File(fileURL.getFile()))); 
  34.         String API = properties.getProperty(APIName); 
  35.     //构造url请求 
  36.     StringBuilder url = new StringBuilder(API); 
  37.     if(params!=null && params.size()>0) { 
  38.         url.append("?"); 
  39.         for(Map.Entry entry : params.entrySet()) { 
  40.         url.append(entry.getKey()+"="+entry.getValue()+"&"); 
  41.     } 
  42.         url.substring(0, url.length()-1); 
  43.     } 
  44.     //实例化get方法   
  45.     HttpGet httpget = new HttpGet(url.toString());  
  46.     //执行get请求 
  47.         response = httpclient.execute(httpget); 
  48.         if(response.getStatusLine().getStatusCode()==200) { 
  49.             content = EntityUtils.toString(response.getEntity(),"utf-8"); 
  50.         } 
  51.     } catch (IOException e) { 
  52.         e.printStackTrace(); 
  53.     } 
  54. return content; 
  55. }    

执行完毕后返回API提供的数据。

相关文章

站点信息