HttpClient发送get请求

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/aixp88/article/details/62422088

HttpClient 4.5发送get请求示例代码

import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class Test {

    public static void main(String args[]){


        String url = "http://www.baidu.com";
        // 根据地址发送get请求
        HttpGet request = new HttpGet(url);
        // 获取当前客户端对象
        HttpClient httpClient = HttpClientBuilder.create().build();

        try {
            // 通过请求对象获取响应对象
            HttpResponse response = httpClient.execute(request);

            // 判断网络连接状态码是否正常(0--200都数正常)
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                //获取响应实体
                String result = EntityUtils.toString(response.getEntity(),"utf-8");

                System.out.println(result);
            } 

        } catch (ClientProtocolException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();
        }

    }

}

猜你喜欢

转载自blog.csdn.net/aixp88/article/details/62422088