HttpURLConnection: writing into OutputStream, get response - java

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?

Related

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

HttpURLConnection response is incorrect

When using this code below to make a get request:
private String get(String inurl, Map headers, boolean followredirects) throws MalformedURLException, IOException {
URL url = new URL(inurl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setInstanceFollowRedirects(followredirects);
// Add headers to request.
Iterator entries = headers.entrySet().iterator();
while (entries.hasNext()) {
Entry thisEntry = (Entry) entries.next();
Object key = thisEntry.getKey();
Object value = thisEntry.getValue();
connection.addRequestProperty((String)key, (String)value);
}
// Attempt to parse
InputStream stream = connection.getInputStream();
InputStreamReader isReader = new InputStreamReader(stream );
BufferedReader br = new BufferedReader(isReader );
System.out.println(br.readLine());
// Disconnect
connection.disconnect();
return connection.getHeaderField("Location");
}
The resulting response is completely nonsensical (e.g ���:ks�6��﯐9�rђ� e��u�n�qש�v���"uI*�W��s)
However I can see in Wireshark that the response is HTML/XML and nothing like the string above. I've tried a myriad of different methods for parsing the InputStream but I get the same result each time.
Please note: this only happens when it's HTML/XML, plain HTML works.
Why is the response coming back in this format?
Thanks in advance!
=== SOLVED ===
Gah, got it!
The server is compressing the response when it contains XML, so I needed to use GZIPInputStream instead of InputSream.
GZIPInputStream stream = new GZIPInputStream(connection.getInputStream());
Thanks anyway!
use an UTF-8 encoding in input stream like below
InputStreamReader isReader = new InputStreamReader(stream, "UTF-8");

Unable to write to Text File Exist in FTP server

I use below code to write to text file that exists in FTP server.but got java.net.MalformedURLException
URL url = new URL("ftp://p#g.com:g#1234#ftp.xyz.com/testjar/2014-03-06-p.txt;type=i");
URLConnection urlc = url.openConnection();
OutputStream os = urlc.getOutputStream(); // To upload
OutputStream buffer = new BufferedOutputStream(os);
ObjectOutput output = new ObjectOutputStream(buffer);
output.writeObject("hiiiii");
buffer.close();
os.close();
output.close();
above username and password is not real but its demo that looks like real.
anybody know how to solve this issue or other method to write into a .txt file,let me inform.
Edit1:also my username and pass contains # char and in pass number is there.
Full Error:
java.net.MalformedURLException: For input string: "g#1234#ftp.xyz.com"
at java.net.URL.<init>(URL.java:619)
at java.net.URL.<init>(URL.java:482)
at java.net.URL.<init>(URL.java:431)
at CreateFolder.uploadfile(CreateFolder.java:39)
at CreateFolder.main(CreateFolder.java:74)
Caused by: java.lang.NumberFormatException: For input string: "g#1234#ftp.xyz.com"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at java.net.URLStreamHandler.parseURL(URLStreamHandler.java:217)
at java.net.URL.<init>(URL.java:614)
... 4 more
You didn't provide us with the error you get but I see couple of issues here:
Connection string: I know it's an example but if real user/pass contain '#' char, the URL won't be parsed.
ObjectOutputStream class is intended to write object data so it can be reconstructed by ObjectInputStream (see here). It's not for writing textual files. If all you need is writing String to stream better use PrintStream
So the revised example will be:
try {
URL url = new URL("ftp://user:pass#ftp.xyz.com/testjar/2014-03-06-p.txt;type=i");
URLConnection urlc = url.openConnection();
OutputStream os = urlc.getOutputStream(); // To upload
OutputStream buffer = new BufferedOutputStream(os);
PrintStream output = new PrintStream(buffer);
output.print("hiiiii");
} catch (IOException ex) {
ex.printStackTrace();
} finally {
output.close();
buffer.close();
os.close();
}
Solved:
replace '#' character with '%40' at parse time it will automatically got converted to '#'.
URL url = new URL("ftp://p%40g.com:g%401234#ftp.xyz.com/testjar/2014-03-06-p.txt;type=i");
URLConnection urlc = url.openConnection();
OutputStream os = urlc.getOutputStream(); // To upload
OutputStream buffer = new BufferedOutputStream(os);
PrintStream output = new PrintStream(buffer);
output.print("wowhii");
buffer.close();
os.close();
output.close();

How Do You Upload a File to a Server With PHP using Java [duplicate]

This question already has answers here:
How to send PUT, DELETE HTTP request in HttpURLConnection?
(8 answers)
Closed 9 years ago.
I have a Java applet that needs to upload a file from the user's computer to the server.
I am unable to add other libraries (such as com.apache). Is there a low level way of doing so.
Currently, I have a php file on the server which contains:
//Sets the target path for the upload.
$target_path = "spelling/";
$_FILES = $_POST;
var_dump($_FILES);
move_uploaded_file($_FILES["tmp_name"], $target_path . $_FILES["name"]);
?>
Currently my Java program is sending parameters via POST to this php file.
It sends these parameters by POST using the following code:
try {
//Creates a new URL containing the php file that writes files on the ec2.
url = new URL(WEB_ADDRESS + phpFile);
//Opens this connection and allows for the connection to output.
connection = url.openConnection();
connection.setDoOutput(true);
//Creates a new streamwriter based on the output stream of the connection.
OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
//Writes the parameters to the php file on the ec2 server.
wr.write(data);
wr.flush();
//Gets the response from the server.
//Creates a buffered input reader from the input stream of the connection.
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
//Loops through and reads the response. Loops until reaches null line.
while ((line = rd.readLine()) != null) {
//Prints to console.
System.out.println(line);
}
//Closes reader and writer.
wr.close();
rd.close();
} catch (Exception e) {
e.printStackTrace();
}
This works for POST'ing data but when I try to send a file using this method, nothing happens (no response from the server nor is the file uploaded).
If anyone has any hints I would be grateful :)
Are you using java.net.URLConnection?
You may want to get some help on this page:
http://www.codejava.net/java-se/networking/upload-files-by-sending-multipart-request-programmatically
Here is the main part:
boundary = "===" + System.currentTimeMillis() + "===";
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
httpConn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
true);
But, you will need to have the php script be on the same server where your applet came from.

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