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

HttpClient是Apache HttpComponents項目下的一個組件,是Commons-HttpClient的升級版,二者api調用寫法也很相似。文中所使用到的軟件版本:Java 1.8.0_19一、HttpClient 4.5.10。html

一、服務端

參見Java調用Http接口(1)--編寫服務端 java

二、調用

2.一、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.二、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.三、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.四、上傳文件及發送鍵值對數據

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.五、完整例子

package com.inspur.demo.http;

import java.io.File;
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.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 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();
        multi();
    }

}
View Code
相關文章
相關標籤/搜索