如何在android中使用带响应的HttpURLConnection(Content-Type:text / html)?

时间:2017-11-03 02:29:43

标签: android html httpurlconnection

我的qustion是关于应该使用HttpURLConnection在Android中编写的代码来获取响应吗?

请求和2响应如下:

请求 [头 授权:******]

响应
[代码:302, 头 (Content-Type:text / html)]

响应
[代码:302, 头 (Content-Type:text / html)]

代码:

private void makeHttpRequest(URL url)抛出IOException {

    String redirectUrl;

    HttpURLConnection urlConnection = null;
    try {
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setReadTimeout(10000 /* milliseconds */);
        urlConnection.setConnectTimeout(15000 /* milliseconds */);
        urlConnection.addRequestProperty("Authorization", "********");
        urlConnection.connect();

        if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK
                || urlConnection.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM
                || urlConnection.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP) {

            redirectUrl = urlConnection.getHeaderField("Content-Type");

        } else {
            Log.e(LOG_TAG, "Error redirect response code: " + urlConnection.getResponseCode());
        }

    } catch (IOException e) {
        Log.e(LOG_TAG, "Problem retrieving", e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

使用

urlConnection.setRequestProperty("Content-type", "text/html");