Java,如何从HTTP POST方法获取连接响应代码?

时间:2013-04-03 07:36:54

标签: http-post http-get

我在使用以下代码时可以获取数据:

    private static String getHttpPostContent(String address, String token) {    
        try {
            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(address);

            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            pairs.add(new BasicNameValuePair("token", token));
            post.setEntity(new UrlEncodedFormEntity(pairs));

            HttpResponse httpResponse = client.execute(post);
            HttpEntity entity = httpResponse.getEntity();
            String serverResponse = EntityUtils.toString(entity);

            return serverResponse;

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

根据我的文档,如果发生错误,服务器发送错误418告诉我发生了错误。我不知道怎么抓住它?

当我使用HTTP GET方法时,有一种方法可以检查响应代码,如下所示:

int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) 
...

HTTP POST方法有类似的方法吗?

1 个答案:

答案 0 :(得分:0)

您是否尝试过观察httpResponse.getStatusLine().getStatusCode()

相关问题