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

时间:2016-12-01 17:25:52

标签: java url httpurlconnection protocolexception

我有以下代码

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(conn.getResponseCode() == 200){
    logger.debug("Success");
} else {                 
    logger.debug("Time out set for 30 seconds");
} 

考虑到代码完全按原样导致java.net.ProtocolException,有没有办法继续获取服务器响应并执行conn.getOutputStream();?按什么顺序?除了显而易见的报道问题之外,没有获得回应的后果是什么?

1 个答案:

答案 0 :(得分:2)

问题是,一旦收到响应代码,您就发送了帖子。在您的代码中,在获得响应之前,您不必向输出流写入任何内容。所以,你基本上没有发送任何内容(只是头信息),获取响应代码,然后再次尝试写入,这是不允许的。您需要做的是首先写入输出流,然后像这样得到响应代码:

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");
    } 
}

这是一个小教程:

Reading and Writing Tutorial