首页 文章

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

提问于
浏览
0

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

请求和 2 响应如下:

要求[1]

响应
[2]

响应
[3]

代码:

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

    使用

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

相关问题