处理HttpUrlConnection重定向的判断

private void requestNetData () {
try {
    URL url = new URL("http://www.toutiao.com/stream/widget/local_weather/data/?city=%E5%8C%97%E4%BA%AC");
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setRequestMethod("GET");
    urlConnection.setReadTimeout(5000);
    urlConnection.setConnectTimeout(5000);


    if (urlConnection.getResponseCode() == 200) {
        InputStream inputStream = urlConnection.getInputStream();
        String s = streamToString(inputStream);
        //解析
        Gson gson = new Gson();
        ResultData resultData = gson.fromJson(s, ResultData.class);
        Message msg = Message.obtain();
        msg.obj = resultData;
        mHandler.sendMessage(msg);


    } else if (urlConnection.getResponseCode() == 301 || urlConnection.getResponseCode() == 302) {
        //得到重定向的地址
        String location = urlConnection.getHeaderField("Location");
        URL u1 = new URL(location);
        HttpURLConnection uc1 = (HttpURLConnection) u1.openConnection();
        uc1.setRequestMethod("GET");
        uc1.setConnectTimeout(5000);
        uc1.setReadTimeout(5000);
        if (uc1.getResponseCode() == 200) {
            InputStream is1 = uc1.getInputStream();
            String s1 = streamToString(is1);
            //解析
            Gson gson = new Gson();
            ResultData rd = gson.fromJson(s1, ResultData.class);
            Message msg = Message.obtain();
            msg.obj = rd;
            mHandler.sendMessage(msg);
        }


    } else {
    }

} catch (Exception e) {
    e.printStackTrace();
}}
          
展开阅读全文

没有更多推荐了,返回首页