2016-12-01 49 views
0

我有以下代碼我必須從服務器獲取響應代碼嗎?

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();?按什麼順序?除了明顯的報告問題之外,沒有獲得迴應的後果是什麼?

回答

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

+0

謝謝你的回答和教程 – Mushy