Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

java - Sometimes HttpURLConnection.getInputStream executes too slowly

We have next code.
Sometimes we should wait 10-20-40 seconds on the last line.
What can be the problem?

Java 1.4

URL url = ...;
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.connect();
OutputStream out = conn.getOutputStream();
ObjectOutputStream outStream = new ObjectOutputStream(out);
try
{
   outStream.writeObject(objArray);
}
finally
{
   outStream.close();
}

InputStream input = conn.getInputStream();

UPDATED:
Next code fixes the problem IN ECLIPSE.
But it still DOES NOT WORK via Java WebStart:(

HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
conn.setDoInput(true);  
conn.setDoOutput(true);  
conn.setUseCaches(false);  
System.setProperty("http.keepAlive", "false");  //<---------------
conn.connect();  

But why?

UPDATED one more time!
Bug was fixed! :)

We worked with connections not in one class but in two.
And there is following line in the second class:

URL url = ...  
HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
conn.setRequestProperty("Content-Length", "1000");  //<------------
conn.connect();  

Note: setRequestProperty("Content-Length", "1000") is root cause of the problem.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

'We had a similar issue which is caused by buggy keep-alive in old Java. Add this before connect to see if it helps,

conn.setRequestProperty("Connection", "close");

or

System.setProperty("http.keepAlive", "false");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...