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

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

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

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



乱码问题: 
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);
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值