使用“apache httpclient”和“httpurlconnection”时为什么http状态代码不同?

时间:2018-05-24 02:48:19

标签: java apache http httpclient httpurlconnection

我现在正在实施微博oauth2登录。 我使用了两种方法 - apache httpclient和httpurlconnection。 但HTTP响应代码在两种情况下是不同的。

String accessToken = "***";
String weiboUid = "***";

try {
        URL url = new URL("https://api.weibo.com/2/users/show.json?access_token=" + accessToken + "&uid=" + weiboUid);
        conn2 = (HttpURLConnection) url.openConnection();
        conn2.setConnectTimeout(10000);
        conn2.setDoInput(true);
        conn2.setDoOutput(true);
        conn2.setRequestMethod("GET");

        outputStream = conn2.getOutputStream();
        outputStream.flush();

        int responseCode = conn2.getResponseCode();

        StringBuilder responseReq = new StringBuilder();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            String line;
            BufferedReader br = new BufferedReader(new InputStreamReader(conn2.getInputStream()));
            while ((line = br.readLine()) != null) {
                responseReq.append(line).append("\n");
            }
            br.close();
        } else {
            throw new Exception("data not exist!");
        }

        String result = responseReq.toString().trim();
        JsonParser parser = new JsonParser();
        JsonObject jsonObject = parser.parse(result).getAsJsonObject();
        String nickname = jsonObject.get("screen_name").getAsString();

        System.out.println(nickname);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (conn2 != null)
            conn2.disconnect();
    }

在这种情况下,responseCode为405并且已经执行了“throw new Exception("data not exist!");”。

但是当我使用apache httpclient库时,响应代码为200,我可以获取登录信息。

String accessToken = "***";
String weiboUid = "***";
    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet("https://api.weibo.com/2/users/show.json?access_token=" + accessToken + "&uid=" + weiboUid);

    try {
        HttpResponse response = client.execute(request);
        System.out.println("Response Code : " +
                response.getStatusLine().getStatusCode());

        BufferedReader rd = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }

        System.out.println(result.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }

apache httpclient和httpurlconnection有什么区别?

1 个答案:

答案 0 :(得分:0)

GET请求没有内容。

使用conn2.setDoOutput(true);删除outputStream和所有行。