I'm trying to post a file to a ASP.NET WEB API (C#) Server with a local Java application.
Basically I'm trying to reproduce the following HTML code in Java SE:
<form name="form1" method="post" enctype="multipart/form-data" action="http://localhost:50447/api/files/">
<div>
<label for="image1">Image File</label>
<input name="image1" type="file" />
</div>
<div>
<input type="submit" value="Submit" />
</div>
What's the simplest way to do this? I'd like to avoid using Apache..
Something like:
String urlToConnect = "http://localhost:50447/api/files/";
String paramToSend = "";
File fileToUpload = new File("C:/Users/aa/Desktop/sample_signed.pdf");
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
URLConnection connection = null;
try {
connection = new URL(urlToConnect).openConnection();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
connection.setDoOutput(true); // This sets request method to POST.
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
PrintWriter writer = null;
try {
writer = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
writer.println("--" + boundary);
writer.println("Content-Disposition: form-data; name=\"paramToSend\"");
writer.println("Content-Type: text/plain; charset=UTF-8");
writer.println();
writer.println(paramToSend);
writer.println("--" + boundary);
writer.println("Content-Disposition: form-data; name=\"fileToUpload\"; filename=\"sample_signed.pdf\"");
writer.println("Content-Type: text/plain; charset=UTF-8");
writer.println();
BufferedReader reader = null;
try {
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileToUpload), "UTF-8"));
} catch (UnsupportedEncodingException | FileNotFoundException e1) {
e1.printStackTrace();
}
try {
for (String line; (line = reader.readLine()) != null;) {
writer.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
} finally {
if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
}
writer.println("--" + boundary + "--");
} catch (UnsupportedEncodingException e2) {
e2.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
} finally {
if (writer != null) writer.close();
}
// Connection is lazily executed whenever you request any status.
int responseCode = 0;
try {
responseCode = ((HttpURLConnection) connection).getResponseCode();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(responseCode);
Using only URLConnections.. This code isn't working properly.. It sends the file, but some content is lost and I don't know why.. My HTML sample works perfectly..
Can you help me?
Thank you for your attention,
Best Regards.
You are using a reader and writer combination, while you are transferring binary data. You should use streams when working with binary data.
So instead of a BufferedReader, use a normal InputStream buffered to read the file and do not wrap the output stream you get from the URLConnection.
Read bytes instead of strings in the read loop. So replace the part starting with BufferedReader until the finally just before the boundary write with:
OutputStream output = connection.getOutputStream();
InputStream fileIn = new FileInputStream(fileToUpload);
try {
byte[] buffer = new byte[4096];
int length;
while ((length = fileIn.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
output.flush();
} finally {
if (fileIn != null) try { fileIn.close(); } catch (IOException logOrIgnore) {}
}
Solution: Another approach, using DataOutputStream.
FileInputStream fileInputStream = new FileInputStream(absolutePath);
URL url = new URL("http://localhost:50447/api/files/");
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", filename);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
System.out.println(serverResponseMessage);
fileInputStream.close();
dos.flush();
dos.close();
Related
I am trying to upload byte array to http server using post method from android. But i am getting always connection reset or Broken pipe error. Could pls help me understand where i am doing wrong.
int bufferBytes = 131072; // 128 KB
Random r = new Random( System.currentTimeMillis() );
int fileName = 10000 + r.nextInt(20000);
String urlParameters = ""+ StringUtils.leftPad("abcdefgh", bufferBytes, "abcdefgh");
byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
String CRLF = "\r\n";
String boundary = "-----------------------******";
OutputStream out = null;
HttpURLConnection urlConnection = null;
PrintWriter writer = null;
try {
URL url = new URL("host");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setConnectTimeout(10*1000) ; // 15 Sec time out
System.setProperty("http.keepAlive", "false");
urlConnection.setChunkedStreamingMode(1024);
//urlConnection.setRequestProperty("Keep-Alive", "false");
urlConnection.setRequestProperty("connection", "close");
urlConnection.setUseCaches (false);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Accept", "text/xml,application/x ml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
urlConnection.setConnectTimeout(15*1000) ; // 15 Sec time out
urlConnection.setRequestProperty( "Content-Length", Integer.toString( postData.length ));
urlConnection.setRequestProperty("Accept-Encoding", "identity");
urlConnection.setRequestProperty("Transfer-Encoding", "chunked") ;
urlConnection.connect();
out = urlConnection.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(out, "UTF-8"), true);
// Send normal param.
writer.append("100000").append(CRLF);
writer.append(boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"success_action_status\"").append(CRLF);
writer.append("201").append(CRLF);
writer.append(boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"Content-Type\"").append(CRLF);
writer.append("image/jpeg").append(CRLF);
writer.append(boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"x-amz-acl\"").append(CRLF);
writer.append("public-read").append(CRLF);
writer.append(boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"key\"").append(CRLF);
writer.append("images/237615.jpg").append(CRLF);
writer.append(boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"FileName\"").append(CRLF);
writer.append("ul+"+fileName+".jpg").append(CRLF);
writer.append(boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"file\"; filename=ul" +fileName).append(CRLF);
writer.append("Content-Type: image/jpeg").append(CRLF); // Text file itself must be saved in this charset!
writer.append(CRLF).flush();
out.flush(); // Important before continuing with writer!
writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
long startTime = System.currentTimeMillis();
while (true){
out.write(postData);
out.flush();
if(System.currentTimeMillis() - startTime > 10000)
break;
}
Log.d("Upload" , " Upload is success");
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
}finally {
try {
if(writer != null)
writer.close();
if(out != null)
out.close();
if(urlConnection != null)
urlConnection.disconnect();
}catch (Exception e){
e.printStackTrace();
}
}
If i comment the below line i am getting the java.net.SocketException: Connection reset else i am getting the java.net.SocketException: Broken pipe
System.setProperty("http.keepAlive", "false");
Don't set the content length. It isn't required at all in chunked transfer mode, and it isn't required at all in Java HttpURLConnection, which sets it for you when necessary.
I am using HttpURLConnection class to upload text file to my Apache server. For server side code I used php to handle the POST request. I was wondering , how the same thing can be done other then PHP, or the PHP is the best way to handle file uploading on server side?..Also I cannot find any jsp or java code on server side to handle http post request..any code snippet that does same thing other then PHP would be really helpful..Cause I think java or jsp would be easier to code ..Thanks
Android code to upload file:
public void upLoad()
{
String exsistingFileName = path+"//"+"test.txt";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
try {
// ------------------ CLIENT REQUEST
Log.e(Tag, "Inside second Method");
FileInputStream fileInputStream = new FileInputStream(new File(
exsistingFileName));
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: post-data; name=uploadedfile;filename="
+ exsistingFileName + "" + lineEnd);
dos.writeBytes(lineEnd);
Log.e(Tag, "Headers are written");
// create a buffer of maximum size
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1000;
// int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bytesAvailable];
// read file and write it into form...
int bytesRead = fileInputStream.read(buffer, 0, bytesAvailable);
while (bytesRead > 0) {
dos.write(buffer, 0, bytesAvailable);
bytesAvailable = fileInputStream.available();
bytesAvailable = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bytesAvailable);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
Log.e(Tag, "File is written");
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
Log.e(Tag, "error: " + ex.getMessage(), ex);
}
catch (IOException ioe) {
Log.e(Tag, "error: " + ioe.getMessage(), ioe);
}
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(conn
.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
Log.e("Dialoge Box", "Message: " + line);
}
rd.close();
} catch (IOException ioex) {
Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex);
}
}
Php code on server side :
<?php
$target_path = "./upload/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
I think there is no correct answer for this question, PHP can be good as JSP or even ASP. Depends on your platform preference or if you are planning on having a tomcat vs apache server or even a microsoft iis server. Personally I think PHP/Apache is a good choice.
I'm trying to upload image to a image hosting site (fastpic.ru) but I can't get right response as I expected. I used fiddler to check would I send right param and everything seems are fine but I can't get right response. Could you guide me how to upload and get response in proper way?
Right response I mean I should receive something like http://fastpic.ru/session/2012/0425/Y6sEtGjtT1.html but I only receive http://fastpic.ru/index.php
Thank you
This is my code
String urlToConnect = "http://fastpic.ru/uploadmulti";
String boundary = Long.toHexString(System.currentTimeMillis()); // Generate random boundary
URLConnection connection = new URL(urlToConnect).openConnection();
connection.setDoOutput(true); // This sets request method to POST.
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
OutputStream output = null;
PrintWriter writer = null;
try {
output = connection.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"), true); // true = Autoflush, important!
writer.println("-----------------------------" + boundary);
writer.println("Content-Disposition: form-data; name=\"file[]\"; filename=\"" + fileToUpload.getName() + "\"");
writer.println("Content-Type: image/jpeg");
writer.println();
InputStream input = null;
try {
input = new FileInputStream(fileToUpload);
byte[] buffer = new byte[1024];
for (int length = 0; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
output.flush();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException logOrIgnore) {
}
}
}
writer.println();
writer.println("-----------------------------" + boundary);
writer.println("Content-Disposition: form-data; name=\"submit\"");
writer.println();
writer.println("Загрузить");
writer.println("-----------------------------" + boundary);
writer.println("Content-Disposition: form-data; name=\"uploading\"");
writer.println();
writer.println("1");
writer.println("-----------------------------" + boundary + "--");
} finally {
if (writer != null) {
writer.close();
}
}
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
in.close();
If it isn't returning the right output, there is probably something incorrect with the input.
I would recommend using the Apache HTTP components, such as MultipartEntity at http://hc.apache.org/httpcomponents-client-ga/httpmime/apidocs/org/apache/http/entity/mime/MultipartEntity.html for POSTing this kind of data. If you're trying to manually encode your data, it would be quite easy to make a simple mistake that'll stop the entire thing from working. There are a lot of examples using the Apache components, and its pretty simple to use.
So, I'm trying to upload a file to my PHP server. I found some code online which works, but I also need to include values for things like user authentication and where on the server the file should be uploaded. I am relatively new to HTTP communication and the code I found below uses terms/code that I have never heard of before, multipart/form-data Content-Type and Content-Disposition specifically. So if someone could tell me how to include the values I need, provide a different method entirely, or just explain those 3 terms to me like I'm five, I'd greatly appreciate it. Here's my code:
public static void upload(String path, String section, Context c){
Log.i("path", path);
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String responseFromServer = "";
String urlString = c.getString(R.string.server) + "upload.php";
try {
// ------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(
path));
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
+ path + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
Log.e("Debug", "File is written");
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
} catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
// ------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream(conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null) {
Log.e("Debug", "Server Response " + str);
}
inStream.close();
} catch (IOException ioex) {
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
}
**Edit: Just to be a little more clear, I would like it to where in my PHP script I could access values like $_REQUEST['path'] (which might = '/documents/' or something) as well as the actual file with $_FILES['uploadedfile']
String urlToSendRequest = "https://example.net";
String targetDomain = "example.net";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpHost targetHost = new HttpHost(targetDomain, 80, "http");
HttpPost httpPost = new HttpPost(urlToSendRequest);
// Make sure the server knows what kind of a response we will accept
// httpPost.addHeader("Accept", "text/xml");
// Also be sure to tell the server what kind of content we are sending
httpPost.addHeader("Content-Type", "application/xml");
StringEntity entity = new StringEntity("<input>test</input>", "UTF-8");
entity.setContentType("application/xml");
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, context);
Reader r = new InputStreamReader(response.getEntity().getContent());
I'm trying to make a program that uploads a image to a webserver that accepts multipart file-uploads.
More specificly i want to make a http POST request to http://iqs.me that sends a file in the variable "pic".
I've made a lot of tries but i don't know if i've even been close. The hardest part seems to be to get a HttpURLConnection to make a request of the type POST. The response i get looks like it makes a GET.
(And i want to do this without any third party libs)
UPDATE: non-working code goes here (no errors but doesn't seem to do a POST):
HttpURLConnection conn = null;
BufferedReader br = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
InputStream is = null;
OutputStream os = null;
boolean ret = false;
String StrMessage = "";
String exsistingFileName = "myScreenShot.png";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "http://iqs.local.com/index.php";
try{
FileInputStream fileInputStream = new FileInputStream( new File(exsistingFileName) );
URL url = new URL(urlString);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"pic\";" + " filename=\"" + exsistingFileName +"\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0){
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
fileInputStream.close();
dos.flush();
dos.close();
}catch (MalformedURLException ex){
System.out.println("Error:"+ex);
}catch (IOException ioe){
System.out.println("Error:"+ioe);
}
try{
inStream = new DataInputStream ( conn.getInputStream() );
String str;
while (( str = inStream.readLine()) != null){
System.out.println(str);
}
inStream.close();
}catch (IOException ioex){
System.out.println("Error: "+ioex);
}
Two things:
Make sure you call setRequestMethod to set the HTTP request to be a POST. You should be warned that doing multipart POST requests by hand is difficult and error-prone.
If you're running on *NIX, the tool netcat is very useful for debugging this stuff. Run
netcat -l -p 3000
and point your program to port 3000; you'll see exactly what the program is sending (Control-C to close it afterwards).
I have used this and found it useful in multipart file upload
File f = new File(filePath);
PostMethod filePost = new PostMethod(url);
Part[] parts = { new FilePart("file", f) };
filePost.setRequestEntity(new MultipartRequestEntity(parts,
filePost.getParams()));
HttpClient client = new HttpClient();
status = client.executeMethod(filePost);