• JAVA中使用Apache HttpComponents Client的进行GET/POST请求使用案例


    一、简述需求

      平时我们需要在JAVA中进行GET、POST、PUT、DELETE等请求时,使用第三方jar包会比较简单。常用的工具包有:

      1、https://github.com/kevinsawicki/http-request (对应Maven包:http://mvnrepository.com/artifact/com.github.kevinsawicki/http-request)

      2、http://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient/4.5.5

      第1个包使用起来比较简单,如下:

    package songxingzhu.utils.request;
    
    import com.github.kevinsawicki.http.HttpRequest;
    
    public class RequestUtils {
        private static final String defaultCharset = "utf-8";
        private static final int connectTimeoutInMissecond = 10000;
        private static final int readTimeoutInMissecond = 30000;
    
        public static RequestResult getJsonText(String url, String charset)  {
            if (charset == null) charset = defaultCharset;
            HttpRequest request = HttpRequest.get(url).connectTimeout(connectTimeoutInMissecond).readTimeout(readTimeoutInMissecond);
            String body = request.body(charset);
            int code = request.code();
            request.disconnect();
            return new RequestResult(body, code);
        }
    
    }

      本文主要讲第2个包的使用。

    二、开发过程

      如下图所示:

    import org.apache.http.HttpEntity;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.client.utils.HttpClientUtils;
    import org.apache.http.client.utils.URIBuilder;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;
    import org.junit.Test;
    
    import java.io.IOException;
    import java.net.URI;
    import java.net.URISyntaxException;
    import java.nio.charset.Charset;
    import java.util.ArrayList;
    import java.util.List;
    
    public class HttpClientTest {
        @Test
        public void get() throws IOException {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpGet request = new HttpGet("https://xingzhu-song.chinacloudsites.cn/kvMapping?orgId=b11647e8-0e36-44fd-84fa-262c4fcfbe43");
            request.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0");
            CloseableHttpResponse response = httpClient.execute(request);
            HttpEntity entry = response.getEntity();
            int code = response.getStatusLine().getStatusCode();
            System.out.println("	code:" + code);
            String result = EntityUtils.toString(entry);
            System.out.println("	result:" + result);
            HttpClientUtils.closeQuietly(response);
            HttpClientUtils.closeQuietly(httpClient);
        }
    
        @Test
        public void postForm() throws IOException {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost request = new HttpPost("https://xingzhu-song.chinacloudsites.cn/monitoring/metric/definitions");
            List<NameValuePair> list = new ArrayList<>();
            list.add(new BasicNameValuePair("orgId", "b11647e8-0e36-44fd-84fa-262c4fcfbe43"));
            list.add(new BasicNameValuePair("instanceId", "1b0acfbb-d7f2-4f0d-a026-734c686ee4ba"));
            request.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
            CloseableHttpResponse response = httpClient.execute(request);
            HttpEntity entry = response.getEntity();
            int code = response.getStatusLine().getStatusCode();
            System.out.println("	code:" + code);
            String result = EntityUtils.toString(entry);
            System.out.println("	result:" + result);
            HttpClientUtils.closeQuietly(response);
            HttpClientUtils.closeQuietly(httpClient);
        }
    
        @Test
        public void postJSON() throws IOException {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost request = new HttpPost("https://xingzhu-song.chinacloudsites.cn/kvMapping/valid?orgId=b11647e8-0e36-44fd-84fa-262c4fcfbe43");
            String body = "{" +
                    "  "serviceId": "pip",
    " +
                    "  "key": "pipDnsLabel",
    " +
                    "  "value": "abcdefg",
    " +
                    "  "dependenceOn": {"pipLocation":"chinanorth"}
    " +
                    "}";
            request.setEntity(new StringEntity(body, "UTF-8"));
            request.setHeader("content-type", "application/json");
            CloseableHttpResponse response = httpClient.execute(request);
            HttpEntity entry = response.getEntity();
            int code = response.getStatusLine().getStatusCode();
            System.out.println("	code:" + code);
            String result = EntityUtils.toString(entry);
            System.out.println("	result:" + result);
            HttpClientUtils.closeQuietly(response);
            HttpClientUtils.closeQuietly(httpClient);
        }
    
        @Test
        public void testUrl() throws URISyntaxException {
            URIBuilder uriBuilder = new URIBuilder("https://xingzhu-song.chinacloudsites.cn");
            uriBuilder.setPath("kvMapping");
            uriBuilder.setCharset(Charset.forName("UTF-8"));
            uriBuilder.setParameter("key1", "value1");
            uriBuilder.setParameter("key2", "value2");
            //uriBuilder.setUserInfo("username","password"); //https://username:password@xingzhu-song.chinacloudsites.cn/kvMapping?key1=value1&key2=value2
            URI uri = uriBuilder.build();
            System.out.println(uri);//https://xingzhu-song.chinacloudsites.cn/kvMapping?key1=value1&key2=value2
        }
    }

      

  • 相关阅读:
    C++ Primer高速入门之六:数组和指针
    C++ Primer高速入门之六:数组和指针
    C++ Primer高速入门之六:数组和指针
    大学生毕业卖蔬菜,成就财富梦想
    美女毕业去养牛,创造自主牛肉品牌
    情侣合开夫妻店,爱情和努力让他们生活走向光明
    从3万元创业资金到年销售3亿元,看他是如何做到的?
    “海归”创办服装公司,全国竟拥有2000多家网点?
    90后卖地瓜,仅仅一个月就可以赚2万元
    老头创业弄养殖,每亩收入3万元,水蛭为啥这么值钱?
  • 原文地址:https://www.cnblogs.com/songxingzhu/p/9015117.html
Copyright © 2020-2023  润新知