HttpClient远程访问

1.1 调用流程

HttpClient远程访问

2.1 入门案例

2.1.1 添加jar包

 <!--添加httpClient jar包 -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
    </dependency>

2.1.2 编辑入门案例

public class TestHttpClient {

/**
 * 1.实例化HttpClient客户端对象
 * 2.定义url地址
 * 3.定义请求类型
 * 4.发起httpClient请求
 * 5.获取响应结果 分析状态码信息  200 404 500 504 502
 * 6.获取结果,进行后续操作
 */
@Test
public void testGet() throws IOException {
    HttpClient httpClient = HttpClients.createDefault();
    String url = "http://www.baidu.com";
    HttpGet httpGet = new HttpGet(url);
    HttpResponse httpResponse = httpClient.execute(httpGet);
    if(httpResponse.getStatusLine().getStatusCode() == 200){
        //表示请求一切正常
        HttpEntity httpEntity = httpResponse.getEntity();//获取响应结果实体对象
        String result  = EntityUtils.toString(httpEntity, "UTF-8");
        System.out.println(result);
    }else{
        //表示请求有误
        System.out.println("请求结果有误!!!");
    }
 }
}
上一篇:ASP.NET Core扩展库


下一篇:Java测试开发--HttpClient常规用法(九)