简体   繁体   English

HttpUrlConnection:从非 200OK 获取响应正文

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

I'm trying to get a response body from a HttpUrlConnection object when my server doesn't return a 200OK.当我的服务器没有返回 200OK 时,我试图从 HttpUrlConnection 对象获取响应正文。 In my case, I get a 302 redirect and so using getInputStream() doesn't work.就我而言,我得到了 302 重定向,因此使用getInputStream()不起作用。 I tried to use getErrorStream() but this gives me a null object for some reason.我尝试使用getErrorStream()但由于某种原因这给了我一个空对象。 Why am I getting a null object for getErrorStream() when I'm expecting an actual response?当我期待实际响应时,为什么会为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");
        } 
    }

In my code, what I'm seeing as output is:在我的代码中,我看到的输出是:

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

Specifically, the error occurs in the last line of my try clause because it's my getErrorStream() returns a null object and hence I get a nullPointerException.具体来说,错误发生在我的 try 子句的最后一行,因为它是我的getErrorStream()返回一个 null 对象,因此我得到一个 nullPointerException。 Is anyone familiar with this?有没有人熟悉这个? Thanks谢谢

Because 302 is not considered as an error HTTP response code .因为302不被视为错误HTTP 响应代码

Since the response does not start with 4 nor 5 , it is not considered as an erroneous one.由于响应不是以45开头,因此不会被视为错误响应。

Also look at the documentation of HttpURLConnection::getErrorStream :另请查看HttpURLConnection::getErrorStream的文档:

Returns the error stream if the connection failed but the server sent useful data nonetheless.如果连接失败但服务器仍然发送了有用的数据,则返回错误流。 The typical example is when an HTTP server responds with a 404, which will cause a FileNotFoundException to be thrown in connect, but the server sent an HTML help page with suggestions as to what to do.典型的例子是当 HTTP 服务器以 404 响应时,这将导致在连接中抛出 FileNotFoundException,但服务器发送了一个 HTML 帮助页面,其中包含有关如何操作的建议。


Feel free to dig into the source code as well to get the more information and where is everything clear:也可以随意深入研究源代码以获取更多信息以及一切清楚的地方:

@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;
}

Sadly, this information is not included in the documentation, though.遗憾的是,这些信息并未包含在文档中。

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.

相关问题 Android Java:从HttpUrlConnection获取响应正文 - Android Java: Get Response Body from HttpUrlConnection Spring Boot JPA 删除返回 200ok 但不从数据库中删除 - Spring Boot JPA delete returns 200ok but not delete from DB Spring 引导 GET 请求给出 200 OK 状态,但 Postman 返回“ø”作为响应主体 - Spring Boot GET Request gives 200 OK status, but Postman returns "ø" as response body Spring 引导 GET 请求给出 200 OK 状态,但 Postman 返回“[]”作为响应正文 - Spring Boot GET Request gives 200 OK status, but Postman returns "[]" as response body ajax 问题 - firebug 中的 200 OK 但没有响应正文的红色消息 - ajax problem - 200 OK in firebug but red message with no response body spring 引导返回 200 并带有“OK”错误属性附加到正常的主体响应 - spring boot returns 200 with “OK” ErrorAttributes attached to normal body response Spring RestTemplate 用任何非 200 OK 响应交换 POST HttpClientException - Spring RestTemplate exchange POST HttpClientException with any non 200 OK response 200后的HttpURLConnection 403响应 - HttpURLConnection 403 response after 200 无法从 Asterisk 服务器获得 200 OK - Unable to get 200 OK from Asterisk server 如何从HttpURLConnection POST获得响应 - How to get response from HttpURLConnection POST
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM