Apache httpclient不会引发任何异常

时间:2019-11-12 10:59:48

标签: apache exception httpclient

即使我已经尝试捕获,Apache客户端也不会引发任何异常。

我尝试使用错误的URL发出POST请求,但它不会停止并引发任何错误。在我的代码中,它一直持续进行,最后卡在JSON上,因为没有结果返回

public static String getToken(String tokenUri, String loginInfo)
{
    try {
    String result = "";

    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectionRequestTimeout(CONNECTION_TIMEOUT)
            .setConnectTimeout(CONNECTION_TIMEOUT)
            .setSocketTimeout(CONNECTION_TIMEOUT)
            .build();

    HttpPost post = new HttpPost(tokenUri);
    post.setConfig(requestConfig);
    post.addHeader("content-type", "application/json");

    StringBuilder entity = new StringBuilder();
    entity.append(loginInfo);

    // send a JSON data
    post.setEntity(new StringEntity(entity.toString()));

    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse response = httpClient.execute(post);

    result = EntityUtils.toString(response.getEntity());

    JSONObject responseBodyComplete = new JSONObject(result);
    JSONObject responseBodyData = responseBodyComplete.getJSONObject("data");
    String token = responseBodyData.getString("token");

    return token;
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    return null;
}

0 个答案:

没有答案