HttpURLConnection:在一些Android设备和模拟器中获取307响应代码

时间:2015-02-21 13:49:51

标签: android httpurlconnection http-status-codes

我正在使用HttpURLConnection对特定网址执行GET请求。在一些仿真器和设备中,它运行良好,我得到200代码,在其他情况下,我得到307代码。有人可以告诉我这是什么问题吗?

这是我的代码:

URL cnx =新网址(网址); HttpURLConnection urlCon =(HttpURLConnection)cnx.openConnection(); urlCon.setRequestMethod( “GET”); urlCon.setConnectTimeout((int)timeout); urlCon.setReadTimeout((int)timeout); urlCon.connect(); int code = urlCon.getResponseCode(); if(code!= 200){return null; }

1 个答案:

答案 0 :(得分:0)

我通过使用DefaultHttpClient而不是HttpURLConnection解决了我的问题。如果有人遇到同样的问题,这是代码:

public String WebServiceCall(String url){

    try {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);

        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

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

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "utf-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        is.close();
        res = sb.toString();

    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    return res;
}