android multipart/form-data POST get 400 error - java

I should send text/image files to one website using POST method.
But, I couldn't get 200 code after my MainActivity.
my code block
String crlf = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
System.out.println("[Request] routine is started.");
URL url = new URL(_url);
urlConn = (HttpURLConnection) url.openConnection();
// [2-1]. urlConn setting
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setUseCaches(false);
urlConn.setRequestMethod("POST"); // URL method : POST.
urlConn.setRequestProperty("Connection", "keep-alive");
urlConn.setRequestProperty("Cache-Control", "no-cache");
urlConn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
// [2-2]. parameter send and read data
OutputStream os = urlConn.getOutputStream();
DataOutputStream request = new DataOutputStream(os);
// Write key and values
// 1. Access Key
request.writeBytes(twoHyphens + boundary + crlf);
request.writeBytes("Content-Disposition: form-data; name=\"accessKey\"" + crlf);
request.writeBytes("Content-Type: application/json" + crlf);
request.writeBytes(crlf);
request.writeBytes(accessKey + crlf);
// 2. Image data
request.writeBytes(twoHyphens + boundary + crlf);
request.writeBytes("Content-Disposition: form-data; name=\"files\"" + crlf);
request.writeBytes("Content-Type: image/jpeg" + crlf);
request.writeBytes(crlf);
request.write(imageBytes);
request.writeBytes(crlf);
request.writeBytes(twoHyphens + boundary + twoHyphens + crlf);
request.flush();
request.close();
int response_code = urlConn.getResponseCode();
System.out.println("Connection response code : [" + response_code + "]");
I think my DataOutputStream code is not bad, but I get 400 error:
I/System.out: [Request] routine is started.
D/EGL_emulation: app_time_stats: avg=45.59ms min=8.56ms max=670.08ms count=23
I/System.out: Connection response code : [400]
I/System.out: [doInBackground] output : Response Code : 400
I/System.out: [onPostExecute] routine is started.
I/System.out: [onPostExecute] output : Response Code : 400
What's wrong?

Related

Android HttpURLConnection POST Request with image/jpeg

I am trying to send image in POST request with HttpURLConnection. I have next code:
String i3 = String.valueOf(System.currentTimeMillis());
ByteArrayOutputStream i4 = new ByteArrayOutputStream();
i4.write(("--" + i3 + System.lineSeparator()
+ "Content-Disposition: form-data; name=\"" + I1.this.i2 + "\"; filename=\"" + I1.this.i2 + ".jpg\"" + System.lineSeparator()
+ "Content-Type: image/jpeg" + System.lineSeparator()
+ "Content-Length: " + String.valueOf(i2.this.i1.length) + System.lineSeparator() + System.lineSeparator()).getBytes());
i4.flush();
i4.write(i2.this.i1);
i4.flush();
i4.write((System.lineSeparator() + System.lineSeparator() + "--" + i3 + "--").getBytes());
i4.flush();
i4.close();
HttpURLConnection i5 = (HttpURLConnection) new URL(myUrl).openConnection();
i5.setRequestMethod("POST");
i5.setDoOutput(true);
i5.setRequestProperty("User-Agent", "Mozilla/5.0");
i5.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + i3);
i5.setFixedLengthStreamingMode(i4.toByteArray().length);
i5.connect();
OutputStream i6 = i5.getOutputStream();
i6.write(i4.toByteArray());
i6.flush();
i6.close();
System.out.println(i5.getResponseCode() + " " + i5.getResponseMessage());
i5.disconnect();
But when I'm trying to get response code/message of connection application throws me an exception:
07-28 12:15:00.722: java.io.IOException: unexpected end of stream on
Connection{123.456.789.012:80, proxy=DIRECT# hostAddress=123.456.789.012
cipherSuite=none protocol=http/1.1} (recycle count=0)
Maybe problem is my post request is bad or having syntax errors? Can you help me and say what's wrong, please.
I tested this code on Java application on windows! The result of request is 200 OK. Conclusion: Something wrong with android! But I still don't know what concretically.
I found the solution! This ugly strings System.lineSeparator() need to be replaced with old kind \r\n! Great.

Error code:500 received in HttpsURLConnection

I am sending a HttpsURLConnection request to a server which requires a basic auth with it. I have provided the authorization value and verified it as well. But I'm getting a Http status 500: Internal Server error. Here is my code:
public String httptest(String url, File f, String username, String password) throws Exception {
// Task attachments endpoint
HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
// Set basic auth header
String apiKey = username + ":" + password;
String basicAuth = "Basic " + new String(new Base64().encode(apiKey.getBytes()));
connection.setRequestProperty("Authorization", basicAuth);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
logger.info("basicAuth: " + basicAuth);
// Indicate a POST request
connection.setDoOutput(true);
// A unique boundary to use for the multipart/form-data
String boundary = Long.toHexString(System.currentTimeMillis());
String fboundary = "----WebKitFormBoundary" + boundary + "u0gW";
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + fboundary);
// Construct the body of the request
logger.info("boundary: " + fboundary);
PrintWriter writer = null;
try {
writer = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
String fileName = f.getName();
String ffname = fileName.substring(fileName.lastIndexOf("\\")+1);
writer.append("--" + fboundary).append(LINE_FEED);
writer.append("Content-Disposition: multipart/form-data; name=\"file\"; filename=\"" + ffname + "\"").append(LINE_FEED);
writer.append("Content-Type: application/x-zip-compressed").append(LINE_FEED);
writer.append(LINE_FEED);
logger.info("fileName: " + fileName);
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-8"));
for (String line; (line = reader.readLine()) != null; ) {
writer.append(line).append(LINE_FEED);
}
} finally {
if (reader != null) try {
reader.close();
} catch (IOException logOrIgnore) {
}
}
writer.append(LINE_FEED);
writer.append("----" + fboundary).append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();
writer.close();
} catch (Exception e) {
System.out.append("Exception writing file" + e);
} finally {
if (writer != null) writer.close();
}
logger.info("ResponseCode: " + connection.getResponseCode());
//System.out.println(connection.getResponseCode()); // Should be 200
return connection.getResponseMessage();
}
When I send the same request through postman client, It works fine. Here are the headers from the postman request:
Authorization: Basic c2dveWFsQHF1YXJrLmNvbTpRdWFyazEyMw==
Cache-Control: no-cache Postman-Token:
d6fac5f0-e844-9bac-2bce-51580fdd5557 Content-Type:
multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
----WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="file"; filename="Tiger522.zip" Content-Type:
application/x-zip-compressed
----WebKitFormBoundary7MA4YWxkTrZu0gW
Please tell me what to do?
I can see two possible errors:
As StephaneM pointed out: The content-disposition of the file upload must be "form-data", not "multipart/form-data":
writer.append("Content-Disposition: form-data; name=\"file\";
filename=\"" + ffname + "\"").append(LINE_FEED);
You specify "Content-Type: application/x-zip-compressed" for the file upload. This means zip format. You are however just writing a file in there, using InputStreamReader. This does not seem to be a zip format that you are writing.

JAVA HttpsConnection POST send image and text

I am trying to send a text and a image via HTTP POST and I always get a 400 error. I would like to use it to send a image via Telegram bot and I am using the code provided in this answer with a text and bite parameters https://stackoverflow.com/a/2793153/1970613 with small modifications.
What could be the error ?
String param = "chat_id=mi_id&photo=";
String charset = "UTF-8";
String request = "https://api.telegram.org/bot-botCOde/sendPhoto";
URL url = new URL( request );
File binaryFile = new File("/home/joseantonio/imagen.jpg");
String CRLF = "\r\n"; // Line separator required by multipart/form-data.
String boundary = Long.toHexString(System.currentTimeMillis());
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "charset", "utf-8");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
conn.setUseCaches( false );
try {
OutputStream output = conn.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);
writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
writer.append(CRLF).append(param).append(CRLF).flush();
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF);
writer.append("Content-Type: image/jpg").append(CRLF);
writer.append("Content-Transfer-Encoding: binary").append(CRLF);
writer.append(CRLF).flush();
Files.copy(binaryFile.toPath(), output);
output.flush(); // Important before continuing with writer!
writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
// End of multipart/form-data.
writer.append("--" + boundary + "--").append(CRLF).flush();
int responseCode2 = conn.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + request);
System.out.println("Response Code : " + responseCode2);```
I believe the fact that you are using https url is the cause of the error you are getting. You need to handle things a little different when you are submitting to an https url. See an example here

getting a invalid_request_body error when i try to void a document

When trying to void a in-progress document, I received the invalid_request_body error(The request body is missing or improperly formatted. Data at the root level is invalid). Is there something missing on the request body ?
url = baseURL + "/envelopes/" + envelopeId;
body = "";
// re-use connection object for second request...
conn = InitializeRequest(url, "PUT", body, authenticationHeader);
String requestBody = "\r\n\r\n--BOUNDARY\r\n" +
"Accept: application/xml" +
"Content-Type: application/xml\r\n" +
"\r\n" +
body + "\r\n\r\n--BOUNDARY\r\n" +
"status: voided\r\n" +
"voidedReason: Time-out\r\n" +
"\r\n";
String reqBody2 = "\r\n" + "--BOUNDARY--\r\n\r\n";
DataOutputStream dos= new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(requestBody.toString());
//dos.write(bytes);
dos.writeBytes(reqBody2.toString());
dos.flush();
dos.close();
System.out.println("STEP 2: Retrieving envelope information for envelope " + envelopeId + ".\n");
status = conn.getResponseCode(); // triggers the request
if( status != 200 ) { // 200 = OK
System.out.println(conn);
System.out.println(status);
errorParse(conn, status);
throw new RuntimeException();
}
// display results
response = getResponseBody(conn);
Following up with your comments for the benefit of the community...
This is the request body that worked for you in the end:
request body## String requestBody = "<envelope>" + "<status>voided</status>" + "<voidedReason>user aborted</voidedReason>" + "</envelope>"

Blackberry Push Notification - Not receiving on Device

I am struggling for getting message on devices since last some days. At last I think to take a help from experts.
Below are the steps I have followed.
I have created Push initiator in core java.
note: I am getting response code : 200 OK - I assume that this message reaches to PPG for further processing - But not confirmed.
I have used sample Push Enabled Application for Blackberry Device -
I could able to register and waiting for messages on perticular port. but I am not receiving any messages :(
Now I am helpless, My question is
1. Does I am in right track
2. Is there any way to find out how to debug and where my messages are hanging.
I am waiting for some positive solution. Thanks in advance..
Here is my actual code for Push initiator for J2SE
StringBuffer dataToSend = new StringBuffer();
dataToSend.append("--" + BOUNDARY);
dataToSend.append(" ");
dataToSend.append("Content-Type: application/xml; charset=UTF-8");
dataToSend.append(" ");
dataToSend.append("<?xml version=\"1.0\"?>");
dataToSend
.append("<!DOCTYPE pap PUBLIC \"-//WAPFORUM//DTD PAP 2.1//EN\" \"http://www.openmobilealliance.org/tech/DTD/pap_2.1.dtd\" [<?wap-pap-ver supported-versions=\"2.0\"?>]>");
dataToSend.append("<pap>");
String myPushId = ""+ new Random().nextInt();
dataToSend.append("<push-message push-id=\"" + myPushId
+ "\" source-reference=\"" + applicationID + "\">");
dataToSend.append("<address address-value=\"" + pin + "\"/>");
dataToSend
.append("<quality-of-service delivery-method=\"confirmed\"/>");
dataToSend.append("</push-message>");
dataToSend.append("</pap> ");
dataToSend.append("--" + BOUNDARY);
dataToSend.append(" Content-Encoding: binary ");
dataToSend.append(" Content-Type: text/plain ");
dataToSend.append(" ");
dataToSend.append("X-Wap-Application-Id: " + applicationID);
dataToSend.append(" X-Rim-Push-Type: browser-channel X-Rim-Push-Title: Test X-Rim-Push-Unread-Icon: http://rim.com/icon_new.png ");
dataToSend.append("X-Rim-Push-Read-Icon: http://rim.com/icon_viewed.png ");
dataToSend.append("X-Rim-Delete-URL: http://rim.com/ReceiveDelete ");
dataToSend.append("X-Rim-Transcode-Content: */* ");
dataToSend.append("Cache-Control: max-age=3600 ");
dataToSend.append(msg);
dataToSend.append("--" + BOUNDARY + "--");
dataToSend.append(" ");
printer(dataToSend.toString());
// printer("-------------------------------------------------------------------");
String authInfo = applicationID + ":" + userPW;
String encoding = new sun.misc.BASE64Encoder().encode(authInfo
.getBytes());
// authInfo = Base64.encode(authInfo.getBytes());
authInfo = "Basic " + encoding;
printer(authInfo);
URL url;
HttpURLConnection connection = null;
try {
// Create connection
url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"multipart/related; boundary=" + BOUNDARY
+ "; type=application/xml");
connection.setRequestProperty("User-Agent",
"BlackBerry Push Service SDK/1.0");
// / connection.setRequestProperty("Authorization",
// authInfo.getBytes().toString());
connection.setRequestProperty("Authorization", authInfo);
connection.setRequestProperty("Accept",
"text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2");
connection.setRequestProperty("Connection", "keep-alive");
connection.setRequestProperty("Content-Length",
"" + dataToSend.length());
connection.setDoInput(true);
connection.setDoOutput(true);
// Send request
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.writeBytes(dataToSend.toString());
wr.flush();
wr.close();
printer("" + connection.getResponseCode());
String response = connection.getResponseMessage();
printer(response);
// return response;

Categories