2016-03-30 42 views
3

我開發了一個調度器應用,當我做的測試中,我得到異常IOException異常:寫這是代碼的不足部分數據引發錯誤:HttpURLConnection的java.io.IOException異常:沒有足夠的數據寫入

final int responseCode = connection.getResponseCode(); 

final HttpURLConnection connection = (HttpURLConnection) new URL(getUrl()).openConnection(); 
final int timeout =200; 
final HttpRequestContext data = getData();//data contains the data send in the request to dispatche 
connection.setConnectTimeout(timeout); 
for (final Entry<String, List<String>> entry : data.getHeaders().entrySet()) { 
    for (final String value : entry.getValue()) { 
    connection.setRequestProperty(entry.getKey(), value); 
    } 
} 
connection.setUseCaches(false); 
connection.setDoInput(true); 
connection.setDoOutput(true); 
if (data.getContentLength() > 0) { 
    connection.setFixedLengthStreamingMode(data.getContentLength()); 
} 
connection.setReadTimeout(timeout); 
connection.setRequestMethod(data.getMethod()); 
final int responseCode = connection.getResponseCode(); 
if (responseCode == HttpURLConnection.HTTP_OK) { 
    final HttpRequestContext data = getData(); 

if (ArrayUtils.isEmpty(data.getBody())) { 
    LOGGER.debug("No data to send"); 
} else { 
    IOUtils.write(data.getBody(), connection.getOutputStream()); 
} 
} 

日誌:

java.io.IOException: insufficient data written 
at sun.net.www.protocol.http.HttpURLConnection$StreamingOutputStream.close(HttpURLConnection.java:3501) 
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1470) 
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441) 
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480) 
at com.dhl.dispatcher.HttpRequestWriter.doRun(HttpRequestWriter.java:78) 
at com.dhl.dispatcher.AbstractRequestWriter.run(AbstractRequestWriter.java:73) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) 
at java.lang.Thread.run(Thread.java:745) 

感謝您的幫助。

+0

請發表完整的日誌! –

+0

爲什麼將content-length設置爲請求主體的長度?你爲什麼設置它,但沒有發送任何東西回來? – EJP

+0

我更新了答案 – djodjo

回答

0

你永遠不發送任何數據,但設置

connection.setFixedLengthStreamingMode(data.getContentLength()); 

你需要做的水木清華這樣u得到響應之前:

 DataOutputStream out = new DataOutputStream(connection.getOutputStream()); 
     out.write(body); 
     out.close(); 

UPDATE: 做

final int responseCode = connection.getResponseCode();

ma kes請求

您必須在此之前添加正文。

+0

我更新了代碼以瞭解洞mecanisme – Sabrin

+0

謝謝。我通過在connection.getResponseCode()之前設置主體來解決問題。 – Sabrin

+0

歡迎!順便說一句,如果你剛剛開始寫你的Android客戶端,我建議你嘗試https://github.com/apptik/jus它基於凌空,但更多的演變和更容易:) – djodjo

0

下面的代碼可以,如果不是正在使用被刪除:

if (data.getContentLength() > 0) { 
    connection.setFixedLengthStreamingMode(data.getContentLength()); 
} 

這是代碼的是造成了insufficient data written例外的部分。

相關問題