I have this current code. The file is in memory on the InputStream in or in test.pdf. I would prefer to only keep in-memory.
FileOutputStream fos = new FileOutputStream(new File("test.pdf"));
// Read file
InputStream in = url.openStream();
while((bufferLength = in.read(buffer)) != -1) {
fos.write(buffer, 0, bufferLength);
}
fos.flush();
// Close connections
fos.close();
in.close();
System.out.println("GOT DOCUMENT");
String submitURl = "https://someURL/submit";
// Send data
HttpURLConnection conn = (HttpURLConnection) new URL(submitURl).openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type","multipart/form-data");
conn.setRequestProperty("User-Agent", "Test Agent");
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.flush();
How do I post this file to the /submit URL. What am I missing here?
Related
I have an app that needs to send an image to a server. Right now I'm doing it like this:
//We have a variable "image" that is the Bitmap that we want to send
File imagesFolder = new File(getCacheDir(), "images");
File file = null;
try {
if(imagesFolder.exists() || imagesFolder.mkdirs()) {
file = new File(imagesFolder, "input.jpg");
FileOutputStream stream = new FileOutputStream(file);
//checkWifiOnAndConnected returns true if wifi is on and false if mobile data is being used
image.compress(Bitmap.CompressFormat.JPEG, checkWifiOnAndConnected() ? 90 : 80, stream);
stream.flush();
stream.close();
}
} catch (IOException e) {
Log.d("Error", "IOException while trying to write file for sharing: " + e.getMessage());
}
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addPart("file", new FileBody(file));
HttpEntity entity = builder.build();
URL url = new URL(serverUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(40000);
conn.setConnectTimeout(40000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(entity.getContentLength());
conn.addRequestProperty(entity.getContentType().getName(), entity.getContentType().getValue());
OutputStream os = conn.getOutputStream();
entity.writeTo(os);
os.close();
conn.connect();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK)
Log.e("UPLOAD", "HTTP 200 OK.");
It works, but it's kinda slow, specially when using mobile data (obviously). And I would like to know if there's a more efficient and faster way to send this image.
Trying to downloading a file from url (this service is developed in .net soap request) using java (HttpURLConnection class) i'm getting HttpURLConnection.HTTP_OK file successfully downloaded with empty content (i.e 0kb)
Code:
String userCredentials = "abc:cde";
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestProperty("Authorization","Basic "+ userCredentials);
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "Application/octet-stream");
connection.setChunkedStreamingMode(4096);
connection.setRequestProperty("SOAPAction", url.toString());
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
String saveFilePath = saveDir + File.separator + downloadFileName;
System.out.println(saveFilePath);
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
int bytesRead ;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
Output:
HTTPResponse code : 200
File downloaded with empty
Note: response header
{null=[HTTP/1.1 200 OK], Server=[Microsoft-IIS/8.5], Cache-Control=[private], X-AspNet-Version=[4.0.30319], Content-Length=[0], Date=[Fri, 15 Jun 2018 09:14:07 GMT], X-Powered-By=[ASP.NET]}
You're not connecting resources.
Add connection.connect() before your responseCode = httpurlconnection.http_oksentence.
I'm testing a sample of code but its always error at connection.setDoInput(true);
HttpsURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String urlServer = "https://www.myurl.com/upload.php";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead = 0;
int bytesAvailable = 0;
int bufferSize = 0;
byte[] buffer = null;
int maxBufferSize = 1*1024*1024;
try {
FileInputStream fileInputStream = new FileInputStream(new File(params[0]));
URL url = new URL(urlServer);
connection = (HttpsURLConnection) url.openConnection();
connection.setConnectTimeout(1000);
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
connection.setConnectTimeout(1000);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + params[0] + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
The error log is java.lang.IllegalStateException: Already connected.
I have tried these but none is working:
connection.setRequestProperty("Connection", "close");
connection.disconnect();
connection.setConnectTimeout(1000);
EDIT: even when i didn't call connection.connect(), it's still giving the same error already connected.
You must close the input stream after reading it to end of stream.
You should remove the call to connect(). You have it in the wrong place, but it's automatic and doesn't need to be called at all.
You can also remove the line that sets POST. This is implicit in calling setDoOutput(true).
You can also remove most of that crud in the copy loop. Use a fixed size buffer:
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
Do not use a new buffer per read; do not call available(); do not pass GO; do not collect $200.
Move
connection.connect();
after
connection.setRequestMethod("POST");
There is a very good post about http connections here
The bottom line is that for POSTs you only need the following.
HttpURLConnection connection = (HttpURLConnection) new URL(urlToRead).openConnection();
// setDoOutput(true) implicitly set's the request type to POST
connection.setDoOutput(true);
I'm not sure you need to specify HttpsURLConnection either. You can use HttpURLConnection for connecting to Https sites. Let java do the work for you behind the scenes.
Here is the POST code that I use for json posts
public static String doPostSync(final String urlToRead, final String content) throws IOException {
final String charset = "UTF-8";
// Create the connection
HttpURLConnection connection = (HttpURLConnection) new URL(urlToRead).openConnection();
// setDoOutput(true) implicitly set's the request type to POST
connection.setDoOutput(true);
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-type", "application/json");
// Write to the connection
OutputStream output = connection.getOutputStream();
output.write(content.getBytes(charset));
output.close();
// Check the error stream first, if this is null then there have been no issues with the request
InputStream inputStream = connection.getErrorStream();
if (inputStream == null)
inputStream = connection.getInputStream();
// Read everything from our stream
BufferedReader responseReader = new BufferedReader(new InputStreamReader(inputStream, charset));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = responseReader.readLine()) != null) {
response.append(inputLine);
}
responseReader.close();
return response.toString();
}
Add
if (connection != null) connection.disconnect();
before
connection = (HttpsURLConnection) url.openConnection();
See if problem solved. If yes, it means connection.disconnect() is not called in your original code. Maybe you put connection.disconnect() at the end of your try block, however an exception occurs before it, so it jumps to the catch block and connection.disconnect() is never called.
NOT a duplicate of my other question.
I am sending a POST request like this:
String urlParameters = "a=b&c=d";
String request = "http://www.example.com/";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setUseCaches(false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
connection.disconnect();
How can I read the xml response returned from a HTTP POST request? Particularly, I want to save the response file as a .xml file, and then read it. For my usual GET requests, I use this:
SAXBuilder builder = new SAXBuilder();
URL website = new URL(urlToParse);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream("request.xml");
fos.getChannel().transferFrom(rbc, 0, 1 << 24);
fos.close();
// Do the work
Addendum: I'm using the following code and it works just fine. However, it neglects any spacing and new lines and treats the complete XML contents as a single line. How do I fix it?
InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb1 = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb1.append(line);
}
FileOutputStream f = new FileOutputStream("request.xml");
f.write(sb1.toString().getBytes());
f.close();
br.close();
don't use Readers and readLine() with xml data. use InputStreams and byte[]s.
Thanks to Pangea, I modified his code and this now works:
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer t= transFactory.newTransformer();
t.setOutputProperty(OutputKeys.METHOD, "xml");
t.setOutputProperty(OutputKeys.INDENT,"yes");
Source input = new StreamSource(is);
Result output = new StreamResult(new FileOutputStream("request.xml"));
transFactory.newTransformer().transform(input, output);
I need to send a xml file to the following link\
http://14.140.66.142:80/MSMQ/private$/votes
This is my code.
URL url = new URL("http://14.140.66.142:80/MSMQ/private$/votes");
URLConnection con = url.openConnection();
String document = "C:\\Documents and Settings\\Nagra\\My Documents\\Responseserver\\workingVoting\\VoteSubmitter\\Body.xml";
FileReader fr = new FileReader(document);
// specify that we will send output and accept input
con.setDoInput(true);
con.setDoOutput(true);
char[] buffer = new char[1024*10];
int b_read = 0;
if ((b_read = fr.read(buffer)) != -1)
{
con.setRequestHeader ( "Content-Type", "text/xml" );
con.setRequestProperty("SOAPAction","MSMQMessage");
con.setRequestProperty("Proxy-Accept","NonInteractiveClient" );
con.setRequestProperty("CONNECTION", "close");
con.setRequestProperty("CACHE-CONTROL", "no-cache");
con.setRequestProperty("USER-AGENT", "OpenTV-iAdsResponder_1_0");
OutputStreamWriter writer = new OutputStreamWriter( con.getOutputStream() );
writer.write(buffer, 0, b_read);
PrintWriter pw = new PrintWriter(con.getOutputStream());
pw.write(buffer, 0, b_read);
pw.close();
System.out.println("written");
}
catch( Throwable t )
{
t.printStackTrace( System.out );
}
}
}
I don't Know whether it is right code.If i run this code I am not able to receive the xml file on the server side.Can anyone help me where i gone wrong in my code.
Below is a sample POST operation:
URL url = new URL("http://14.140.66.142:80/MSMQ/private$/votes");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/xml");
OutputStream os = connection.getOutputStream();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
FileReader fileReader = new FileReader("C:\\Documents and Settings\\Nagra\\My Documents\\Responseserver\\workingVoting\\VoteSubmitter\\Body.xml");
StreamSource source = new StreamSource(fileReader);
StreamResult result = new StreamResult(os);
transformer.transform(source, result);
os.flush();
connection.getResponseCode();
connection.disconnect();
There are a couple of issues with the code you have posted.
First, you are reading only 1024*10 characters and you are not sending the whole file if the file has more characters. Second, you are writing the content more than once. Change the code something similar to this.
URL url = new URL("http://14.140.66.142:80/MSMQ/private$/votes");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
String document = "C:\\Documents and Settings\\Nagra\\My Documents\\Responseserver\\workingVoting\\VoteSubmitter\\Body.xml";
FileReader fr = new FileReader(document);
// specify that we will send output and accept input
con.setDoInput(true);
con.setDoOutput(true);
char[] buffer = new char[1024*10];
int b_read = 0;
con.setRequestProperty ( "Content-Type", "text/xml" );
con.setRequestProperty("SOAPAction","MSMQMessage");
con.setRequestProperty("Proxy-Accept","NonInteractiveClient" );
con.setRequestProperty("CONNECTION", "close");
con.setRequestProperty("CACHE-CONTROL", "no-cache");
con.setRequestProperty("USER-AGENT", "OpenTV-iAdsResponder_1_0");
OutputStreamWriter writer = new OutputStreamWriter( con.getOutputStream() );
while ((b_read = fr.read(buffer)) != -1) {
writer.write(buffer, 0, b_read);
}
writer.flush();
writer.close();
fr.close();
int i = con.getResponseCode();
con.disconnect();
System.out.println(String.format("written with response code: %d",i));