Send file from Action to Servlet - java

My goal is to upload a file from an action to a servlet.
Till now, I thought I had it working in this way:
Action: reads file as bytearray, converts it into String and puts String on request
HttpURLConnection conn =null;
String url = "http://myServlet");
URL obj = new URL(url);
conn = (HttpURLConnection) obj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("GET");
StringBuffer requestParams = new StringBuffer();
requestParams.append("fileString");
requestParams.append("=").append(URLEncoder.encode(fileString, "ISO-8859-1"));
//Append more params
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(requestParams.toString());
wr.flush();
conn.getContentLength();
Servlet: get String parameter, converts it back to bytearray and re-creates the file
receivedString = request.getParameter("fileString");
//Convert to bytearray and create file
But I guess this isn't a good solution, cause sometimes the call just fails because of the string (length maybe?)
Which is the right way to send my file? I can't find a way to send the file AND additional informations putting them on the request.

Related

Receiving binary data over HTTP

I have a server which is sending a .png image to a client via a HTTP post request. The .png is stored inside a sqlite3 database, retrieved as a blob and this all works fine; I have tested saving the returned blob to disk and it can be opened as expected. When my client interprets the response, the payload has mysteriously grown in length from 16365 to 16367, inspecting the response string has shown there are some extra '?' characters intermittently in the stream
Testing the server using the ARC plug-in for Chrome has shown the response received there to be the right length, which leads me to believe there is a problem with my client code:
// request
URL url = new URL(targetURL);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", Integer.toString(parameters.getBytes().length));
conn.setRequestProperty("Content-Language", "en-US");
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.getOutputStream().write(parameters.getBytes());
// response
Reader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
for (int c; (c = rd.read()) >=0;)
sb.append((char)c);
String response = sb.toString();
// this String is of length 16367 when it should be 16365
Does anything jump out as being incorrect here? Note I am not doing any kind of character encoding on either side, should I be when using raw image data?
You can use DataInputStream to read the byte stream.
URL url = new URL("http://i.stack.imgur.com/ILTQq.png");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
DataInputStream dis = new DataInputStream(conn.getInputStream());
FileOutputStream fw = new FileOutputStream(new File("/tmp/img.png"));
byte buffer[] = new byte[1024];
int offset = 0;
int bytes;
while ((bytes = dis.read(buffer, offset, buffer.length)) > 0) {
fw.write(buffer, 0, bytes);
}
fw.close();
Alternatively an instance of BufferedImage can be created directly from the URL using ImageIO.read(java.net.URL).
URL url = new URL("http://i.stack.imgur.com/ILTQq.png");
BufferedImage image = ImageIO.read(url);

Send POST and read streaming response

I have a server that takes a POST request and answers with a data stream. I have seen that on URL I can open a connection or a stream. A stream, however, has no method for writing out data:
URL url = new URL("...");
url.openConnection(); //either I open a connection which has a output stream, but no input
url.openStream(); //or I open a stream, but I cannot write anything out
How can I solve this problem elegantly?
Sample code snippet to use OutputStream.
Note: You can set content types & send some URL parameters to the URL only.
URL obj = new URL(url);//some url
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
String urlParams = "fName=xyz&lname=ABC&pin=12345"; // some parameters
wr.writeBytes(urlParams);
wr.flush();
wr.close();
Have a look at detailed explanation in this article1 and article2

Manually hitting a SOAP Service in Java, getting IO.FileNotFound exception

I need to access a .Net SOAP Service manually. All the importers have issues with its WSDL, so I'm just manually creating the XML message, using HttpURLConnection to connect, and then parsing the results. I've wrapped the Http/SOAP call into a function that is supposed to return the results as a string. Here's what I have:
//passed in values: urlAddress, soapAction, soapDocument
URL u = new URL(urlAddress);
URLConnection uc = u.openConnection();
HttpURLConnection connection = (HttpURLConnection) uc;
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("SOAPAction", soapAction);
connection.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
connection.setRequestProperty("Accept","[star]/[star]");
connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
OutputStream out = connection.getOutputStream();
Writer wout = new OutputStreamWriter(out);
//helper function that gets a string from a dom Document
String xmldata = XmlUtils.GetDocumentXml(soapDocument);
wout.write(xmldata);
wout.flush();
wout.close();
// Response
int responseCode = connection.getResponseCode();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String responseString = "";
String outputString = "";
//Write the SOAP message response to a String.
while ((responseString = rd.readLine()) != null) {
outputString = outputString + responseString;
}
return outputString;
My problem is on the line BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); I get a "java.io.FileNotFoundException" with the address that I'm using (i.e. urlAddress). If I paste that address into a browser, it pulls up the Soap Service webpage just fine (address is http://protectpaytest.propay.com/API/SPS.svc). From what I've read, the FileNotFoundException is if the HttpURLConnection returns a 400+ error message. I added the line getResponseCode() just to see what the exact code was, and it's 404. I added the User-Agent and Accept headers from some other pages saying they were needed, but I'm still getting 404.
Are there other headers I'm missing? What else do I need to do to get this call to work (since it works in a browser)?
-shnar

Read Status code

conn = (HttpURLConnection) connectURL.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.connect();
int code = conn.getResponseCode();
I have successfully established a connection. I am trying to pass the information over the internet.When the url is opened via browser I am getting response as
{"status":"0","responseCode":"1001","response":"Wrong Settings."}
For correct status is returned as 1.
Is there any method where I can get the status only.I have been trying the following methods but every time I am getting code (below is code snippet) as -1 irrespect of status code when I am verifying manually via browser
This is a JSON text. You will need to use a JSON library.
int code = conn.getResponseCode();
this method returns http status code, for http status codes see
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
while the response code you want to retrieve is actually the response string returned by the server.
To read this use:
try {
InputStream in = new BufferedInputStream(conn.getInputStream());
readStream(in);//method to read characters from stream.
finally {
urlConnection.disconnect();
}
}
You can add below code for get Response string from your connection.
OutputStream connectionOutput = null;
connectionOutput=connection.getOutputStream();
connectionOutput.write(requestJson.toString().getBytes());
connectionOutput.flush();
connectionOutput.close();
inputStream = new BufferedInputStream(connection.getInputStream());
ByteArrayOutputStream dataCache = new ByteArrayOutputStream();
// Fully read data
byte[] buff = new byte[1024];
int len;
while ((len = inputStream.read(buff)) >= 0) {
dataCache.write(buff, 0, len);
}
// Close streams
dataCache.close();
Now get Response string of json like below.
String jsonString = new String(dataCache.toByteArray()).trim();
JSONObject mJsonobject=new JSONObject(jsonString);
You can now parse your key from this mJsonobject Object.

HttpURLConnection to Tomcat

I am trying to connect from a java desktop application to a jsp Servlet to send a file.
Clientcoding:
HttpURLConnection urlConnection = null;
URL url = null;
url = new URL("http://127.0.0.1:8080/emobile/AddTripMobile");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
OutputStream out = new BufferedOutputStream(
urlConnection.getOutputStream());
out.write(12); //The data to send
out.flush();
If I connect with the desktop application to the server nothing happens.
(I set a breakpoint in the doGet and doPost)
Any suggestions?
You need to add the following :
InputStream is = urlConnection.getInputStream();
out.write(12); //The data to send
out.flush();
Try closing the output stream.

Categories