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 }

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

  • 相关阅读:
    Linux Sever简单笔记(第十二堂课)之linux下的系统故障分析和排查
    Linux Sever简单笔记(第十一堂课)之linux下的备份和恢复及rsync还有inotify和dump以及restore
    Linux Sever简单笔记(第十堂课)之linux下的任务计划及相关的命令
    ubuntu18.04设置apt源(国内)
    shell简单常用脚本实例
    装完ubuntu系统之后,不能ssh正常连接
    mysql主从复制以及读写分离
    复习计划
    linux下dhcp的安装及配置
    日常问题
  • 原文地址:https://www.cnblogs.com/always-online/p/3899502.html
Copyright © 2011-2022 走看看