zoukankan      html  css  js  c++  java
  • java使用httpcomponents发送get请求

    一、适用场景

      在ESTful webservice中,get方法一般都是用来获取数据。我们可以使用httpcomponents组件来完成调用。

      如我们需要发起get请求,携带的参数都是附加到请求的url后面。

      url:"http://www.xxxxx.com/message?id=000010"

    二、代码示例

     1 package com.demo.test;
     2 
     3 import java.io.IOException;
     4 
     5 import org.apache.http.HttpEntity;
     6 import org.apache.http.HttpStatus;
     7 import org.apache.http.client.ClientProtocolException;
     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 Test2 {
    15 
    16     public static String sendInfo(String url, String param) {
    17         String geturl = String.format("%s?id=%s", url, param);
    18         CloseableHttpClient client = HttpClients.createDefault();
    19         HttpGet get = new HttpGet(geturl);
    20         String responseContent = null; // 响应内容
    21         CloseableHttpResponse response = null;
    22         try {
    23             response = client.execute(get);
    24             HttpEntity entity = response.getEntity();// 响应体
    25             if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 正确返回
    26                 responseContent = EntityUtils.toString(entity, "UTF-8");
    27             }
    28         } catch (ClientProtocolException e) {
    29             e.printStackTrace();
    30         } catch (IOException e) {
    31             e.printStackTrace();
    32         } finally {
    33             try {
    34                 if (response != null)
    35                     response.close();
    36                 if (client != null)
    37                     client.close();
    38             } catch (IOException e) {
    39                 e.printStackTrace();
    40             }
    41         }
    42         return responseContent;
    43     }
    44 
    45     public static void main(String[] args) {
    46         String param = "000010";
    47         String result = sendInfo("http://www.xxxxx.com/message", param);
    48         System.out.println(result);
    49     }
    50 }

      请求成功后,后天会打印返回的信息。

  • 相关阅读:
    delphi7 stringgrid 点列头排序
    如何作为一个优秀的ERP实施顾问
    小米生态链去年收入150亿,今年目标200亿
    msys2 安装笔记(可以按照这个关键字搜索)
    MinGW 编译 libsndfile-1.0.25(只要有 MSYS,./configure make make install 就行了)
    Apache Ignite——新一代数据库缓存系统
    VS2015 C#6.0
    Webuploader 大文件分片上传
    requirejs
    require.js
  • 原文地址:https://www.cnblogs.com/always-online/p/3899502.html
Copyright © 2011-2022 走看看