HttpURLConnection to Tomcat - java

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.

Related

HttpURLConnection: writing into OutputStream, get response

I'm using this answer to write into a HttpURLConnection. It works fine and I close the stream and the connection:
MultipartEntityBuilder mb =
MultipartEntityBuilder.create();//org.apache.http.entity.mime
mb.addTextBody("foo", "bar");
mb.addBinaryBody("bin", new File("testFilePath"));
org.apache.http.HttpEntity e = mb.build();
URLConnection conn = new URL("http://127.0.0.1:8080/app").openConnection();
conn.setDoOutput(true);
conn.addRequestProperty(e.getContentType().getName(),
e.getContentType().getValue());//header "Content-Type"...
conn.addRequestProperty("Content-Length",
String.valueOf(e.getContentLength()));
OutputStream fout = conn.getOutputStream();
e.writeTo(fout);//write multi part data...
fout.close();
conn.getInputStream().close();//output of remote url
just fine. However, I would like to know the server's response (json). How would I do that? I tried using:
InputStream input = conn.getInputStream();
String inputString = new Scanner(input, "UTF-8").useDelimiter("\\Z").next();
input.close();
But I get a java.util.NoSuchElementException error.
In the past I've only used the conn.connect() method and then the conn.getInputStream() and it worked fine. Why it doesn't now? How do I fix that error?

Does Java URLConnection send Metadata?

when you open a connection via URLConnection to read the content of a Webpage,
try {
URL url = new URL("https://stackoverflow.com/questions/46939965/does-java-urlconnection-send-metadata");
URLConnection urlConnection = url.openConnection();
HttpURLConnection connection;
connection = (HttpURLConnection) urlConnection;
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String current;
while((current = in.readLine()) != null) {
urlString += current;
}
}catch(IOException e) {
e.printStackTrace();
}
what will Java leave for Information?
Will statistical data like the Webbrowser saved? Will that be the "Java"?
Thx for help,
~Corn
HTTP "metadata" is normally sent in the headers. The one that would indicate the web browser is typically called "USER_AGENT." I do not believe Java will populate these headers for you implicitly.

Download attachment file from URL - JAVA

I am trying to download a file from a URL like below.
http://localhost/attachment.php?attachId=123
It was downloading as a PHP file instead of the attachment. I have tried like this.
url = new URL(sourceURL);
HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
httpcon.addRequestProperty("User-Agent", "Mozilla/4.76");
if(httpcon.getResponseCode()!=404){
InputStream is = httpcon.getInputStream();
Files.copy(is, Paths.get(destinationFile));
}

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

Send file from Action to Servlet

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.

Categories