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.
Related
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?
I'm building a java server which have to handle http requests. I'm trying to handle a GET request and it works partially fine. In the specific case I want to discuss here I want to respond with a Json. This is what i'm doing:
private Socket socket;
OutputStream outputStream = socket.getOutputStream();
String json = gson.toJson(conversazione);
String response =
"HTTP/1.1 200 OK" + CRLF +
"Content-Length: " + (json.getBytes().length)+ CRLF +
"Content-Type: application/json;charset=UTF-8" + CRLF +
"Server: Federico's Java Server" + CRLF +
"Date: " + new Date() + CRLF + CRLF +
json + CRLF + CRLF;
outputStream.write(response.getBytes());
It works, i mean the client receive the status 200 OK but it receive a text instead of the Json. I'm doing a request with Postman and this is what it receive as response:
Are you sure CRLF = "\r\n"? It looks inverted.
"\n\r" might be interpreted as two lines (Unix+MacOS), hence the HTTP header ends after the first line.
Also better call .getBytes(StandardCharsets.UT8).
I think the issue you have is that you are sending the HTTP Headers and the body together, they need to be separate.
A found this article after a quick search which demonstrates this. From the code sample in that article (slightly adjusted to use the values in your sample):
PrintWriter out = new PrintWriter(socket.getOutputStream());
BufferedOutputStream dataOut = new BufferedOutputStream(connect.getOutputStream());
String content = "application/json;charset=UTF-8";
byte[] fileData = json.getBytes();
int fileLength = (int) file.length();
// send HTTP Headers
out.println("HTTP/1.1 200 OK");
out.println("Server: Federico's Java Server");
out.println("Date: " + new Date());
out.println("Content-type: " + content);
out.println("Content-length: " + fileLength);
out.println(); // blank line between headers and content, very important !
out.flush(); // flush character output stream buffer
dataOut.write(fileData, 0, fileLength);
dataOut.flush();
I encourage to go check that article out. My sample above was written manually and my not work as expected.
I'm a stranger to Java, but I'm developing an app with Processing, and I need enlightenment, please.
I'm running a php server on 127.0.0.1:8080 on the root of the .pde below. all my php scripts are bug free, as well as the rest of the Processing code.
after careful analysis, I've learned that the bug is in the function below.
what is the raised exception down under telling me? and how can I fix the code?
//(cont)
void postPicture(){
//load the saved image into an array of bytes
byte[] thisFile=loadBytes(fileName);
//open a new connection to the server
thisClient = new Client(this, "localhost", 80);
//make an HTTP POST request:
thisClient.write("POST " + pictureScriptUrl + " HTTP/1.1\n");
thisClient.write("Host: localhost\n");
//tell the server you're sending the POST in multiple parts
//and send a unique string that will delineate the parts
thisClient.write("Content-Type: multipart/form-data; boundary=");
thisClient.write(boundary + "\n");
//form the beginning of the request
String requestHead ="--" + boundary + "\n";
requestHead +="Content-Disposition: form-data; name=\"file\"; ";
requestHead += "filename=\"" + fileName + "\"\n";
requestHead +="Content-Type: image/jpeg\n\n";
//form the end of the request
String tail="\n\n--" + boundary + "--\n";
//calculate and send the length of the total request
//including the head of the request, the file, and the tail
int contentLength = requestHead.length() + thisFile.length + tail.length();
thisClient.write("Content-Length: " + contentLength + "\n\n");
//send the header of the request, the file and the tail
thisClient.write(requestHead);
thisClient.write(thisFile);
thisClient.write(tail);
}
java.lang.NullPointerException
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
at javax.imageio.stream.FileCacheImageOutputStream.close(FileCacheImageOutputStream.java:238)
at com.sun.imageio.stream.StreamCloser$CloseAction.performAction(StreamCloser.java:130)
at com.sun.imageio.stream.StreamCloser$1.run(StreamCloser.java:74)
at java.lang.Thread.run(Thread.java:745)
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
I need to put in my android applicazion a tool that uses the free service for sending free sms through internet...
I saw that many apps are able to integrate these sevices..
I tried a lot but I have not found anything useful..
So I ask you ... how can I use the gateway of uthsms.net (for example) for send SMS with my Android application?
Sorry for the generic question..but I not found any starting point for resolve this question.
Thanks in advance
Use a Tool like Firebug to see what gets sent when you click the button on the website. I see that a POST-Request is done to uthsms.net with some parameters. You should be able to do the same POST with your app.
These are the parameter:
button: Send SMS
country: (some integer)
gateway: 0
hyderabad: your message
remLen: remaining length??
sindh: number to send sms to (without the +)
x: some integer
y: some integer
To send this POST-request in Android use following code:
URL url = new URL("http://uthsms.net");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String data = URLEncoder.encode("button", "UTF-8") + "="
+ URLEncoder.encode("Send SMS", "UTF-8");
data += "&" + URLEncoder.encode("country", "UTF-8") + "="
+ URLEncoder.encode(country, "UTF-8");
data += "&" + URLEncoder.encode("gateway", "UTF-8") + "="
+ URLEncoder.encode("0", "UTF-8");
data += "&" + URLEncoder.encode("hyderabad", "UTF-8") + "="
+ URLEncoder.encode(message, "UTF-8");
data += "&" + URLEncoder.encode("remLen", "UTF-8") + "="
+ URLEncoder.encode(remLen, "UTF-8");
data += "&" + URLEncoder.encode("sindh", "UTF-8") + "="
+ URLEncoder.encode(number, "UTF-8");
data += "&" + URLEncoder.encode("x", "UTF-8") + "="
+ URLEncoder.encode("0", "UTF-8");
data += "&" + URLEncoder.encode("y", "UTF-8") + "="
+ URLEncoder.encode("0", "UTF-8");
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(
conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader inStream = new BufferedReader(new InputStreamReader((conn.getInputStream())));
result = inStream.readLine();
inStream.close();
The result seems to be a html-document. Somewhere inside you should find the success message, or possible errors.
Try GoogleVoice API. It has documentation, which might help you get started.
Here's a link : https://code.google.com/p/google-voice-java/