简体   繁体   English

我必须从服务器获取响应代码吗?

[英]Must I Get The Response Code From The Server?

I have the following code 我有以下代码

URL url = new URL(pushURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/restService");
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
if(conn.getResponseCode() == 200){
    logger.debug("Success");
} else {                 
    logger.debug("Time out set for 30 seconds");
} 
String input = writer.getBuffer().toString();
OutputStream os = conn.getOutputStream();

If I am not interested in the response from the server, can I remove the following code? 如果我对服务器的响应不感兴趣,是否可以删除以下代码?

 if(conn.getResponseCode() == 200){
    logger.debug("Success");
} else {                 
    logger.debug("Time out set for 30 seconds");
} 

Considering that the code, in it's entirety as it is, causes a java.net.ProtocolException , is there a way to still grab the server response and execute conn.getOutputStream(); 考虑到整个代码本身会导致java.net.ProtocolException ,有没有办法仍然捕获服务器响应并执行conn.getOutputStream(); ? In what order? 以什么顺序? What are the consequences of not obtaining the response aside from the obvious reporting concerns? 除了明显的报告问题之外,没有获得答复会有什么后果?

The problem is that once you get the response code, you have sent your post. 问题在于,一旦获得响应代码,就已经发送了帖子。 In your code, you don't write anything to the output stream before you get the response. 在代码中,在获得响应之前,您无需向输出流写入任何内容。 So, you are essentially sending nothing over the post (just that header info), getting the response code, and then trying to write to it again, which is not allowed. 因此,您实质上没有在帖子上发送任何内容(仅发送该标题信息),获取了响应代码,然后尝试再次写入它,这是不允许的。 What you need to do is write to the output stream first, and then get the response code like so: 您需要做的是先写入输出流,然后获取响应代码,如下所示:

public static void main(String[] args) throws IOException {
    URL url = new URL(pushURL);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/restService");
    conn.setConnectTimeout(30000);
    conn.setReadTimeout(30000);
    String input = writer.getBuffer().toString();
    OutputStream os = conn.getOutputStream();
    for (char c : input.toCharArray()) {
        os.write(c);
    }
    os.close();

    if(conn.getResponseCode() == 200){
        System.out.println("Success");
    } else {                 
        System.out.println("Time out set for 30 seconds");
    } 
}

Here's a little tutorial: 这是一个小教程:

Reading and Writing Tutorial 读写教程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM