天天看點

【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);
    }
           

繼續閱讀