簡體   English   中英

HttpUrlConnection:從非 200OK 獲取響應正文

[英]HttpUrlConnection: Get response body from non 200OK

當我的服務器沒有返回 200OK 時,我試圖從 HttpUrlConnection 對象獲取響應正文。 就我而言,我得到了 302 重定向,因此使用getInputStream()不起作用。 我嘗試使用getErrorStream()但由於某種原因這給了我一個空對象。 當我期待實際響應時,為什么會為getErrorStream()獲取空對象?

public static void main(String[] args) {
        String url = "http://www.google.com/";
        String proxy = "proxy.myproxy.com";
        String port = "8080";
        try {
            URL server = new URL(url);  
            Properties systemProperties = System.getProperties();
            systemProperties.setProperty("http.proxyHost",proxy);
            systemProperties.setProperty("http.proxyPort",port);
            HttpURLConnection connection = (HttpURLConnection)server.openConnection();
            connection.connect();
            System.out.println("Response code:" + connection.getResponseCode());
            System.out.println("Response message:" + connection.getResponseMessage());
            InputStream test = connection.getErrorStream();
            String result = new BufferedReader(new InputStreamReader(test)).lines().collect(Collectors.joining("\n"));
        } catch (Exception e) {
            System.out.println(e);
            System.out.println("error");
        } 
    }

在我的代碼中,我看到的輸出是:

Response code:302
Response message:Object Moved
java.lang.NullPointerException
error

具體來說,錯誤發生在我的 try 子句的最后一行,因為它是我的getErrorStream()返回一個 null 對象,因此我得到一個 nullPointerException。 有沒有人熟悉這個? 謝謝

因為302不被視為錯誤HTTP 響應代碼

由於響應不是以45開頭,因此不會被視為錯誤響應。

另請查看HttpURLConnection::getErrorStream的文檔:

如果連接失敗但服務器仍然發送了有用的數據,則返回錯誤流。 典型的例子是當 HTTP 服務器以 404 響應時,這將導致在連接中拋出 FileNotFoundException,但服務器發送了一個 HTML 幫助頁面,其中包含有關如何操作的建議。


也可以隨意深入研究源代碼以獲取更多信息以及一切清楚的地方:

@Override
public InputStream getErrorStream() {
    if (connected && responseCode >= 400) {
        // Client Error 4xx and Server Error 5xx
        if (errorStream != null) {
            return errorStream;
        } else if (inputStream != null) {
            return inputStream;
        }
    }
    return null;
}

遺憾的是,這些信息並未包含在文檔中。

package com.ketal.pos.sevice;


import com.utsco.model.User;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;

/**
 *
 * @author Jose Luis Uyuni
 */
public class GenericService {

    private static final long serialVersionUID = 0L;

    public static final String HTTPS = "https";
    public static final String HTTP = "http";
    public String port;
    public static String protocolo = HTTP + "://";
    public String dominio;
    private String urlBase = protocolo;
    public String urlService;
    public Integer response;

    public String getPort() {
        return port;
    }

    public void setPort(String port) {
        this.port = port;
    }

    public String getDominio() {
        return dominio;
    }enter code here

    public void setDominio(String dominio) {
        this.dominio = dominio;
    }

    public String getUrlBase() {
        return urlBase;
    }

    public String getUrlService() {
        return urlService;
    }

    public void setUrlService(String urlService) {
        this.urlService = urlService;
    }

    public String getStringResponse(User u, String method, String query, String body) throws MalformedURLException, IOException, Exception {
        String response = null;
        this.urlBase = protocolo + dominio + urlService + query;
        URL url = new URL(urlBase);
        HttpURLConnection conn;
        if (protocolo.contains(HTTPS)) {
            conn = (HttpsURLConnection) url.openConnection();
        } else {
            conn = (HttpURLConnection) url.openConnection();
        }
        conn.setRequestMethod(method);
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("content-type", "application/json; charset=UTF-8");
        if (u != null) {
            conn.setRequestProperty("Authorization", "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(("ketal.org" + ":" + "124578").getBytes()));
        }

        if (!method.equalsIgnoreCase("GET")) {
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Length", Integer.toString(body.length()));
            conn.setRequestProperty("body", body);
        }

        response = "";
        if (conn.getResponseCode() != 200) {
            if (conn.getErrorStream() != null) {
                response = getResponse(conn.getErrorStream());
            }

            
            if (response.equals("")) {
                response = "{\"message\": \"error\" , \"state\": \"error\", \"nroErr\" ;\"" + "0" + "\" }]";
            }
            
        } else {
            response = getResponse(conn.getInputStream());
        }

        conn.disconnect();
        return response;
    }

    public String getResponse(InputStream i) throws IOException {
        String res = "";
        InputStreamReader in = new InputStreamReader(i);
        BufferedReader br = new BufferedReader(in);
        String output;
        while ((output = br.readLine()) != null) {
            res += (output);
        }

        return res;
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM