Java调用Http接口(4)--HttpClient调用Http接口

2019-11-26 16:05:39来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

Java调用Http接口(4)--HttpClient调用Http接口

HttpClient是Apache HttpComponents项目下的一个组件,是Commons-HttpClient的升级版,两者api调用写法也很类似。文中所使用到的软件版本:Java 1.8.0_191、HttpClient 4.5.10。

1、服务端

参见Java调用Http接口(1)--编写服务端 

2、调用

2.1、GET请求

public static void get() {
    try {
        String requestPath = "http://localhost:8080/webframe/demo/test/getUser?userId=1000&userName=" + URLEncoder.encode("李白", "utf-8");
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet get = new HttpGet(requestPath);
        CloseableHttpResponse response = httpClient.execute(get);
        System.out.println("GET返回状态:" + response.getStatusLine());
        HttpEntity responseEntity = response.getEntity();
        System.out.println("GET返回结果:" + EntityUtils.toString(responseEntity));
        
        //流畅api调用
        String result = Request.Get(requestPath).execute().returnContent().toString();
        System.out.println("GET fluent返回结果:" + result);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

2.2、POST请求(发送键值对数据)

public static void post() {
    try {
        String requestPath = "http://localhost:8080/webframe/demo/test/getUser";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(requestPath);
        
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        list.add(new BasicNameValuePair("userId", "1000"));
        list.add(new BasicNameValuePair("userName", "李白"));
        post.setEntity(new UrlEncodedFormEntity(list, "utf-8"));
        
        CloseableHttpResponse response = httpClient.execute(post);
        System.out.println("POST返回状态:" + response.getStatusLine());
        HttpEntity responseEntity = response.getEntity();
        System.out.println("POST返回结果:" + EntityUtils.toString(responseEntity));
        
        //流畅api调用
        String result = Request.Post(requestPath)
                .bodyForm(Form.form().add("userId", "1000").add("userName", "李白").build(), Charset.forName("utf-8"))
                .execute().returnContent().toString();
        System.out.println("POST fluent返回结果:" + result);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

2.3、POST请求(发送JSON数据)

public static void post2() {
    try {
        String requestPath = "http://localhost:8080/webframe/demo/test/addUser";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(requestPath);
        post.setHeader("Content-type", "application/json");
        String param = "{\"userId\": \"1001\",\"userName\":\"杜甫\"}";
        post.setEntity(new StringEntity(param, "utf-8"));
        
        CloseableHttpResponse response = httpClient.execute(post);
        System.out.println("POST json返回状态:" + response.getStatusLine());
        HttpEntity responseEntity = response.getEntity();
        System.out.println("POST josn返回结果:" + EntityUtils.toString(responseEntity));
        
        //流畅api调用
        String result = Request.Post(requestPath)
                .addHeader("Content-type", "application/json")
                .bodyString(param, ContentType.APPLICATION_JSON)
                .execute().returnContent().toString();
        System.out.println("POST json fluent返回结果:" + result);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

2.4、上传文件

public static void upload() {
    try {
        String requestPath = "http://localhost:8080/webframe/demo/test/upload";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(requestPath);
        FileInputStream fileInputStream = new FileInputStream("d:/a.jpg");
        post.setEntity(new InputStreamEntity(fileInputStream));
        
        CloseableHttpResponse response = httpClient.execute(post);
        System.out.println("upload返回状态:" + response.getStatusLine());
        HttpEntity responseEntity = response.getEntity();
        System.out.println("upload返回结果:" + EntityUtils.toString(responseEntity));
        
        //流畅api调用
        String result = Request.Post(requestPath)
                .bodyStream(new FileInputStream("d:/a.jpg"))
                .execute().returnContent().toString();
        System.out.println("upload fluent返回结果:" + result);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

2.5、上传文件及发送键值对数据

public static void multi() {
    try {
        String requestPath = "http://localhost:8080/webframe/demo/test/multi";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(requestPath);
        FileBody file = new FileBody(new File("d:/a.jpg"));
        HttpEntity requestEntity = MultipartEntityBuilder.create()
                  .addPart("file", file)
                  .addPart("param1", new StringBody("参数1", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8")))
                  .addPart("param2", new StringBody("参数2", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8")))
                  .build();
        post.setEntity(requestEntity);
        
        CloseableHttpResponse response = httpClient.execute(post);
        System.out.println("multi返回状态:" + response.getStatusLine());
        HttpEntity responseEntity = response.getEntity();
        System.out.println("multi返回结果:" + EntityUtils.toString(responseEntity));
        
        //流畅api调用
        String result = Request.Post(requestPath)
                .body(MultipartEntityBuilder.create()
                    .addPart("file", file)
                    .addPart("param1", new StringBody("参数1", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8")))
                    .addPart("param2", new StringBody("参数2", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8")))
                    .build())
                .execute().returnContent().toString();
        System.out.println("multi fluent返回结果:" + result);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

2.6、完整例子

package com.inspur.demo.http;

import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.fluent.Form;
import org.apache.http.client.fluent.Request;
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.entity.ContentType;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
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;

/**
 * 通过Commons-HttpClient调用Http接口
 *
 */
public class HttpClientCase {
    /**
     *  GET请求
     */
    public static void get() {
        try {
            String requestPath = "http://localhost:8080/webframe/demo/test/getUser?userId=1000&userName=" + URLEncoder.encode("李白", "utf-8");
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpGet get = new HttpGet(requestPath);
            CloseableHttpResponse response = httpClient.execute(get);
            System.out.println("GET返回状态:" + response.getStatusLine());
            HttpEntity responseEntity = response.getEntity();
            System.out.println("GET返回结果:" + EntityUtils.toString(responseEntity));
            
            //流畅api调用
            String result = Request.Get(requestPath).execute().returnContent().toString();
            System.out.println("GET fluent返回结果:" + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    
    /**
     *  POST请求(发送键值对数据)
     */
    public static void post() {
        try {
            String requestPath = "http://localhost:8080/webframe/demo/test/getUser";
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost post = new HttpPost(requestPath);
            
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            list.add(new BasicNameValuePair("userId", "1000"));
            list.add(new BasicNameValuePair("userName", "李白"));
            post.setEntity(new UrlEncodedFormEntity(list, "utf-8"));
            
            CloseableHttpResponse response = httpClient.execute(post);
            System.out.println("POST返回状态:" + response.getStatusLine());
            HttpEntity responseEntity = response.getEntity();
            System.out.println("POST返回结果:" + EntityUtils.toString(responseEntity));
            
            //流畅api调用
            String result = Request.Post(requestPath)
                    .bodyForm(Form.form().add("userId", "1000").add("userName", "李白").build(), Charset.forName("utf-8"))
                    .execute().returnContent().toString();
            System.out.println("POST fluent返回结果:" + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     *  POST请求(发送json数据)
     */
    public static void post2() {
        try {
            String requestPath = "http://localhost:8080/webframe/demo/test/addUser";
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost post = new HttpPost(requestPath);
            post.setHeader("Content-type", "application/json");
            String param = "{\"userId\": \"1001\",\"userName\":\"杜甫\"}";
            post.setEntity(new StringEntity(param, "utf-8"));
            
            CloseableHttpResponse response = httpClient.execute(post);
            System.out.println("POST json返回状态:" + response.getStatusLine());
            HttpEntity responseEntity = response.getEntity();
            System.out.println("POST josn返回结果:" + EntityUtils.toString(responseEntity));
            
            //流畅api调用
            String result = Request.Post(requestPath)
                    .addHeader("Content-type", "application/json")
                    .bodyString(param, ContentType.APPLICATION_JSON)
                    .execute().returnContent().toString();
            System.out.println("POST json fluent返回结果:" + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 上传文件
     */
    public static void upload() {
        try {
            String requestPath = "http://localhost:8080/webframe/demo/test/upload";
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost post = new HttpPost(requestPath);
            FileInputStream fileInputStream = new FileInputStream("d:/a.jpg");
            post.setEntity(new InputStreamEntity(fileInputStream));
            
            CloseableHttpResponse response = httpClient.execute(post);
            System.out.println("upload返回状态:" + response.getStatusLine());
            HttpEntity responseEntity = response.getEntity();
            System.out.println("upload返回结果:" + EntityUtils.toString(responseEntity));
            
            //流畅api调用
            String result = Request.Post(requestPath)
                    .bodyStream(new FileInputStream("d:/a.jpg"))
                    .execute().returnContent().toString();
            System.out.println("upload fluent返回结果:" + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 上传文件及发送键值对数据
     */
    public static void multi() {
        try {
            String requestPath = "http://localhost:8080/webframe/demo/test/multi";
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost post = new HttpPost(requestPath);
            FileBody file = new FileBody(new File("d:/a.jpg"));
            HttpEntity requestEntity = MultipartEntityBuilder.create()
                    .addPart("file", file)
                    .addPart("param1", new StringBody("参数1", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8")))
                    .addPart("param2", new StringBody("参数2", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8")))
                    .build();
            post.setEntity(requestEntity);
            
            CloseableHttpResponse response = httpClient.execute(post);
            System.out.println("multi返回状态:" + response.getStatusLine());
            HttpEntity responseEntity = response.getEntity();
            System.out.println("multi返回结果:" + EntityUtils.toString(responseEntity));
            
            //流畅api调用
            String result = Request.Post(requestPath)
                    .body(MultipartEntityBuilder.create()
                        .addPart("file", file)
                        .addPart("param1", new StringBody("参数1", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8")))
                        .addPart("param2", new StringBody("参数2", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8")))
                        .build())
                    .execute().returnContent().toString();
            System.out.println("multi fluent返回结果:" + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
        get();
        post();
        post2();
        upload();
        multi();
    }

}
View Code

 

 


原文链接:https://www.cnblogs.com/wuyongyin/p/11933461.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:将Swagger2文档导出为HTML或markdown等格式离线阅读

下一篇:结合RBAC模型讲解权限管理系统需求及表结构创建