Ronon Ronon - 2 months ago 7
Java Question

java httpurlconnection "failed to read: line to long:"

I'm using httpurlconnection for uploading files to different servers.

For some hosts the following code is working and I'm able to upload files, but when I'm trying to upload to another host, I get an error message


"failed to read: line too long: \nContent-Disposition: form-data; name...


What does this error mean? I couldn't find any hints with google. Hope you can help. :)

private void upload(){

response = "";

DataOutputStream outputStream = null;
InputStream inputStream = null;

String twoHyphens = "--";
String boundary = "--------"+Long.toString(System.currentTimeMillis());
String lineEnd = "\n";

try {
File file = getFile();

StringBuffer sb = new StringBuffer();

sb.append(twoHyphens + boundary + lineEnd);
sb.append("Content-Disposition: form-data; name=\"file1\"; filename=\"" + getFilename() +"\"" + lineEnd);
sb.append("Content-Type: " + getMime() + lineEnd);
sb.append("Content-Transfer-Encoding: binary" + lineEnd);
sb.append(lineEnd);

FileInputStream fileInputStream = new FileInputStream(file);

connection = (HttpURLConnection) url.openConnection();


connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setFixedLengthStreamingMode((uploadContainer.getFilesize() + sb.length() + lineEnd.length() + twoHyphens.length() + boundary.length() + twoHyphens.length() + lineEnd.length()));


connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("User-Agent", USER_AGENT);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);

outputStream = new DataOutputStream(connection.getOutputStream());

outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"file1\"; filename=\"" + getFilename() +"\"" + lineEnd);
outputStream.writeBytes("Content-Type: " + getMime() + lineEnd);
outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
outputStream.writeBytes(lineEnd);


int bytesRead = -1;
byte[] buffer = new byte[4096];
boolean cancelled = false;
while ((bytesRead = fileInputStream.read(buffer)) > 0){
outputStream.write(buffer, 0, bytesRead);

if(Thread.currentThread().isInterrupted()){
cancelled = true;
break;
}
}
if(cancelled == false){
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);


outputStream.flush();

inputStream = connection.getInputStream();

response = convertStreamToString(inputStream);

inputStream.close();

} else {
// ...
}
fileInputStream.close();

} catch(Exception e) {/e.printStackTrace();
} finally {
try {
outputStream.close();
} catch (IOException e) {e.printStackTrace();
}
}
}

EJP EJP
Answer
String lineEnd = "\n";

The problem is here. The line terminator in HTTP is defined as \r\n, not \n.

Comments