天天看点

【Java】HttpClient 使用(代码整理)

当客户端不支持调用jackson转换处理response数据时,报406错误。此时可以手动反序列化为一个string串。

406问题: 

方案一、 在服务端手动转json,返回一个字符串。

方案二.、当url 后缀为html,是不能返回json数据的。 需要在web.xml改后缀。

【Java】HttpClient 使用(代码整理)

乱码问题: 

1、 httpClient客户端,在设置实体前设置实体内容的编码。

2、Controller层,在@RequestMapping中使用produces设置响应的MediaType。

Controller层:(最佳方案)

@RequestMapping(value="/httpclient/post.action",produces = MediaType.APPLICATION_JSON_VALUE +";charset=utf-8")
    @ResponseBody
    public String postTest(String name, String password){
        String str = name+";"+ password;
        String json = JsonUtils.objectToJson(str);
        System.out.println(json);
        return json;
    }
           

HttpCilent 端:

@Test
    public void getTest() throws URISyntaxException, IOException {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //包装一个url
        URIBuilder builder = new URIBuilder("http://www.sogou.com/web");
        builder.addParameter("query", "中国");
        //生成get请求
        HttpGet httpGet = new HttpGet(builder.build());
        CloseableHttpResponse response = httpClient.execute(httpGet);
        //获取结果
        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println(statusCode);
        HttpEntity entity = response.getEntity();
        String str = EntityUtils.toString(entity,"utf-8");
        System.out.println(str);
        response.close();
        httpClient.close();
    }
@Test
    public void postWithParamsTest2() throws IOException {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //创建post请求
        HttpPost httpPost = new HttpPost("http://localhost:8082/httpclient/post.action");
        //使用entity模拟一个表单
        List<NameValuePair> list = new ArrayList<>();
        list.add(new BasicNameValuePair("name", "张三"));
        list.add(new BasicNameValuePair("password", "123"));
        //不要采取下面这种方式,post请求在url中直接写中文,不被识别。
//        List<NameValuePair> params = URLEncodedUtils.parse("name=张三&password=123", Charset.forName("utf-8"));
        //在将编码绑定到httpPost请求前,需要设置entity编码,否则乱码。
        HttpEntity httpEntity = new UrlEncodedFormEntity(list,Charset.forName("utf-8"));
        httpPost.setEntity(httpEntity);
        //执行请求
        CloseableHttpResponse response = httpClient.execute(httpPost);
        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println(statusCode);
        HttpEntity entity = response.getEntity();
        String str = EntityUtils.toString(entity,"utf-8");
        System.out.println(str);
    }
           

继续阅读