CloseableHttpClient(二)

package com.cmy.httpClient;

import java.io.IOException;

import org.apache.http.HttpEntity;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Test;


public class HttpClientTest {

    @Test
    public void jUnitTest(){
        get();
    }

    public void get(){
        CloseableHttpClient client = HttpClients.createDefault();
        try {
            HttpGet httpget = new HttpGet("http://www.baidu.com/");
            HttpPost httppost = new HttpPost("http://www.mi.com/en/");
            System.out.println("executing resutlt url: "+httpget.getURI());
            System.out.println("executing resutlt url: "+httppost.getURI());
            System.out.println("executing resutlt url: "+httpget.getMethod());
            System.out.println("executing resutlt url: "+httppost.getMethod());
            
            CloseableHttpResponse response = client.execute(httppost);
            try {
                HttpEntity entity = response.getEntity();
                System.out.println("响应状态: "+response.getStatusLine());
                if(entity!=null){
                    System.out.println("响应长度: "+entity.getContentLength());
                    System.out.println("响应内容: "+EntityUtils.toString(entity));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
    }
}

 

posted @ 2017-01-12 14:47  公众号java-codestack  阅读(395)  评论(0编辑  收藏  举报