Posting with HttpClient,postinghttpclient

來源:互聯網
上載者:User

Posting with HttpClient,postinghttpclient

HttpClient是Java中經常使用的Http Client,總結下HttpClient4中經常使用的post請求用法。

1 Basic Post

使用2個參數進行post請求:

@Testpublic void whenPostRequestUsingHttpClient_thenCorrect()   throws ClientProtocolException, IOException {    CloseableHttpClient client = HttpClients.createDefault();    HttpPost httpPost = new HttpPost("http://www.example.com");     List<NameValuePair> params = new ArrayList<NameValuePair>();    params.add(new BasicNameValuePair("username", "John"));    params.add(new BasicNameValuePair("password", "pass"));    httpPost.setEntity(new UrlEncodedFormEntity(params));     CloseableHttpResponse response = client.execute(httpPost);    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));    client.close();}

2 POST with Authorization

使用Post進行Basic Authentication credentials驗證:

@Testpublic void whenPostRequestWithAuthorizationUsingHttpClient_thenCorrect()  throws ClientProtocolException, IOException, AuthenticationException {    CloseableHttpClient client = HttpClients.createDefault();    HttpPost httpPost = new HttpPost("http://www.example.com");     httpPost.setEntity(new StringEntity("test post"));    UsernamePasswordCredentials creds =       new UsernamePasswordCredentials("John", "pass");    httpPost.addHeader(new BasicScheme().authenticate(creds, httpPost, null));     CloseableHttpResponse response = client.execute(httpPost);    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));    client.close();}

3 Post with JSON

使用JSON body進行post請求:

@Testpublic void whenPostJsonUsingHttpClient_thenCorrect()   throws ClientProtocolException, IOException {    CloseableHttpClient client = HttpClients.createDefault();    HttpPost httpPost = new HttpPost("http://www.example.com");     String json = "{"id":1,"name":"John"}";    StringEntity entity = new StringEntity(json);    httpPost.setEntity(entity);    httpPost.setHeader("Accept", "application/json");    httpPost.setHeader("Content-type", "application/json");     CloseableHttpResponse response = client.execute(httpPost);    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));    client.close();}

4 Post with HttpClient Fluent API

使用Request進行post請求:

@Testpublic void whenPostFormUsingHttpClientFluentAPI_thenCorrect()   throws ClientProtocolException, IOException {    HttpResponse response =       Request.Post("http://www.example.com").bodyForm(        Form.form().add("username", "John").add("password", "pass").build())        .execute().returnResponse();     assertThat(response.getStatusLine().getStatusCode(), equalTo(200));}

5 Post Multipart Request

Post一個Multipart Request:

@Testpublic void whenSendMultipartRequestUsingHttpClient_thenCorrect()   throws ClientProtocolException, IOException {    CloseableHttpClient client = HttpClients.createDefault();    HttpPost httpPost = new HttpPost("http://www.example.com");     MultipartEntityBuilder builder = MultipartEntityBuilder.create();    builder.addTextBody("username", "John");    builder.addTextBody("password", "pass");    builder.addBinaryBody("file", new File("test.txt"),      ContentType.APPLICATION_OCTET_STREAM, "file.ext");     HttpEntity multipart = builder.build();    httpPost.setEntity(multipart);     CloseableHttpResponse response = client.execute(httpPost);    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));    client.close();}

6 Upload a File using HttpClient

使用一個Post請求上傳一個檔案:

@Testpublic void whenUploadFileUsingHttpClient_thenCorrect()   throws ClientProtocolException, IOException {    CloseableHttpClient client = HttpClients.createDefault();    HttpPost httpPost = new HttpPost("http://www.example.com");     MultipartEntityBuilder builder = MultipartEntityBuilder.create();    builder.addBinaryBody("file", new File("test.txt"),      ContentType.APPLICATION_OCTET_STREAM, "file.ext");    HttpEntity multipart = builder.build();     httpPost.setEntity(multipart);     CloseableHttpResponse response = client.execute(httpPost);    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));    client.close();}

7 Get File Upload Progress

使用HttpClient擷取檔案上傳的進度。擴充HttpEntityWrapper 擷取進度。

上傳代碼:

@Testpublic void whenGetUploadFileProgressUsingHttpClient_thenCorrect()  throws ClientProtocolException, IOException {    CloseableHttpClient client = HttpClients.createDefault();    HttpPost httpPost = new HttpPost("http://www.example.com");     MultipartEntityBuilder builder = MultipartEntityBuilder.create();    builder.addBinaryBody("file", new File("test.txt"),       ContentType.APPLICATION_OCTET_STREAM, "file.ext");    HttpEntity multipart = builder.build();     ProgressEntityWrapper.ProgressListener pListener =      new ProgressEntityWrapper.ProgressListener() {        @Override        public void progress(float percentage) {            assertFalse(Float.compare(percentage, 100) > 0);        }    };     httpPost.setEntity(new ProgressEntityWrapper(multipart, pListener));     CloseableHttpResponse response = client.execute(httpPost);    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));    client.close();}

觀察上傳進度介面:

public static interface ProgressListener {    void progress(float percentage);}

擴充了HttpEntityWrapperProgressEntityWrapper:

public class ProgressEntityWrapper extends HttpEntityWrapper {    private ProgressListener listener;     public ProgressEntityWrapper(HttpEntity entity,       ProgressListener listener) {        super(entity);        this.listener = listener;    }     @Override    public void writeTo(OutputStream outstream) throws IOException {        super.writeTo(new CountingOutputStream(outstream,           listener, getContentLength()));    }}

擴充了FilterOutputStreamCountingOutputStream:

public static class CountingOutputStream extends FilterOutputStream {    private ProgressListener listener;    private long transferred;    private long totalBytes;     public CountingOutputStream(      OutputStream out, ProgressListener listener, long totalBytes) {        super(out);        this.listener = listener;        transferred = 0;        this.totalBytes = totalBytes;    }     @Override    public void write(byte[] b, int off, int len) throws IOException {        out.write(b, off, len);        transferred += len;        listener.progress(getCurrentProgress());    }     @Override    public void write(int b) throws IOException {        out.write(b);        transferred++;        listener.progress(getCurrentProgress());    }     private float getCurrentProgress() {        return ((float) transferred / totalBytes) * 100;    }}

總結

簡單舉例說明如何使用Apache HttpClient 4進行各種post請求。做個筆記。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.