HttpClient 基本操作

2023年 10月 5日 52.9k 0

概念

构造http请求并发送

实现

导入依赖

  
    org.apache.httpcomponent  
    httpclient
    4.5.13


发送get请求

@Test  
public void testGET() throws Exception{  
    //创建httpclient对象  
    CloseableHttpClient httpClient = HttpClients.createDefault();  

    //创建请求对象  
    HttpGet httpGet = new HttpGet("http://localhost:8080/user/shop/status");  

    //发送请求,接受响应结果  
    CloseableHttpResponse response = httpClient.execute(httpGet);  

    //获取服务端返回的状态码  
    int statusCode = response.getStatusLine().getStatusCode();  
    System.out.println("服务端返回的状态码为:" + statusCode);  

    HttpEntity entity = response.getEntity();  
    String body = EntityUtils.toString(entity);  
    System.out.println("服务端返回的数据为:" + body);  

    //关闭资源  
    response.close();  
    httpClient.close();  
}

发送post请求

/**  
* 测试通过httpclient发送POST方式的请求  
*/  
@Test  
public void testPOST() throws Exception{  
    // 创建httpclient对象  
    CloseableHttpClient httpClient = HttpClients.createDefault();  

    //创建请求对象  
    HttpPost httpPost = new HttpPost("http://localhost:8080/admin/employee/login");  

    JSONObject jsonObject = new JSONObject();  
    jsonObject.put("username","admin");  
    jsonObject.put("password","123456");  

    StringEntity entity = new StringEntity(jsonObject.toString());  
    //指定请求编码方式  
    entity.setContentEncoding("utf-8");  
    //数据格式  
    entity.setContentType("application/json");  
    httpPost.setEntity(entity);  

    //发送请求  
    CloseableHttpResponse response = httpClient.execute(httpPost);  

    //解析返回结果  
    int statusCode = response.getStatusLine().getStatusCode();  
    System.out.println("响应码为:" + statusCode);  

    HttpEntity entity1 = response.getEntity();  
    String body = EntityUtils.toString(entity1);  
    System.out.println("响应数据为:" + body);  

    //关闭资源  
    response.close();  
    httpClient.close();  
}

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论