how to post parameters - android

i have some code to send some string parameters via POST method to server
my code is this:
public int uploadAghahi(aghahi AghahiToSend) {
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(AghahiToSend.imagePath);
if (!sourceFile.isFile()) {
prgDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
}
});
return 0;
} else {
try {
JSONObject params = new JSONObject();
params.put("mainsubjectid", "1");
params.put("subsubjectid", "22");
params.put("stateid", "144");
params.put("cityid", "144");
params.put("onvan", "سیاسیباسیباشیباشسیباسیبا");
params.put("address", "سیاسیباسیباشیباشسیباسیبا");
params.put("phone", "سیاسیباسیباشیباشسیباسیبا");
params.put("email", "hseify69#gmail.com");
params.put("tozihat", "سیاسیباسیباشیباشسیباسیبا");
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(ADDRESSsendAghahi);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", AghahiToSend.imagePath);
// conn.setRequestProperty("content-type",
// "application/json;charset=UTF-8");
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Type: text/plain; charset=UTF-8"
+ lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"obj\""
+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(params.toString());
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
// Json_Encoder encode=new Json_Encoder();
// call to encode method and assigning response data to variable
// 'data'
// String data=encode.encod_to_json();
// response of encoded data
// System.out.println(data);
// Adding Parameter filepath
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"filepath\""
+ lineEnd);
// dos.writeBytes("Content-Type: text/plain; charset=UTF-8"
// + lineEnd);
// dos.writeBytes("Content-Length: " + name.length() + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(AghahiToSend.imagePath); // mobile_no is String
// variable
dos.writeBytes(lineEnd);
// Adding Parameter media file(audio,video and image)
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ AghahiToSend.imagePath + "\"" + 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);
serverResponseCode = conn.getResponseCode();
serverResponseMessage = conn.getResponseMessage();
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
String line = "";
while ((line = reader.readLine()) != null) {
result += line;
}
Toast.makeText(AddAghahiActivity.this, serverResponseMessage,
Toast.LENGTH_LONG).show();
if (serverResponseCode == 200) {
runOnUiThread(new Runnable() {
public void run() {
}
});
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
}
});
} catch (final Exception e) {
}
});
}
prgDialog.dismiss();
return serverResponseCode;
}
}
i have a problem and it is with encoding Strings.
some of my strings are in persian and when send to server they get changet to other characters like below:
,3ED3ED3~'3E'3ED4
or
*G1'F
How can i send params correctlly?

Find the appropriate encoding for the server, and encode your request with that encoding, and decode the response with that encoding too. For example, the code I did write yesterday on Python:
params = urllib.parse.urlencode({'tool': tool, 'input': full_text, 'token': token}).encode("UTF-8") # Encoding parameters
result = urllib.request.urlopen(api_url, params) # Making request
readed_result = result.read().decode("UTF-8") # Decoding response
The logic is the same in the Java too.
How to find appropriate encoding for server? Check http header for encoding.
For example:

Related

Fail to upload image and video of different format using urlconnection in android

public String uploadFile(String sourceFileUri) {
fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
return "";
}
else
{
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL urls = new URL(url_upload);
conn = (HttpURLConnection) urls.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setChunkedStreamingMode(1024);
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("fileName", fileName);
String cookie=AppController.getInstance().getPrefManger().getCookie();
Log.i("hello","cookie"+cookie);
conn.setRequestProperty("Cookie", cookie);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"albumId\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(selectedAlbumId); // mobile_no is String variable
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"caption\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(caption.getText().toString()); // mobile_no is String variable
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=files;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();
Log.i("hello", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
String temp;
while((temp=in.readLine())!=null)
{
Log.i("hello", "response is"+temp);
}
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
}
});
Log.e("hello", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
}
});
Log.e("hello", "Exception : "+ e.getMessage(), e);
}
return String.valueOf(serverResponseCode);
} // End else block
}
This is my code which i am using to upload image or video to url.But when i upload files of different format the it fails to upload and unhandled type exception occurs.Please help How can i upload images and video of all type format

HttpURLConnection send variables along with multipart data

I am trying to upload a file to web server,and also send two variables along with it. The file uploads correctly but the variables are not available at server side .Here is my code
URL url = new URL(upLoadServerUri);
// 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);
conn.setRequestProperty("from", phone);//here
conn.setRequestProperty("contact", contact);//here
dos = new DataOutputStream(conn.getOutputStream());
String urlParameters = "from=" + phone + "&contact=" + contact;
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
At server side which is PHP i am accessing the variables from and contact using $_SERVER['from'];
Can you point out what am i doing wrong or a new approach to it?
I also tried dos.writeBytes("contact=a&from=b");
I found the solution on this thread:
Sending files using POST with HttpURLConnection
This is what i end typing:
String boundary = "*****";
String lineEnd = "\r\n";
String twoHyphens = "--";
HttpsURLConnection conn = null;
DataOutputStream dos = null;
BufferedReader inStream = null;
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 10*1024*1024;
String urlString = "https://yoururl.com/phpfile.php";
try{
File f = new File("filepath");
String filename = "filename";
FileInputStream fileInputStream = new FileInputStream(f);
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpsURLConnection) 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("enctype", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
conn.setRequestProperty("upfile", filename);
dos = new DataOutputStream( conn.getOutputStream() );
String name = "myvariable";
String value = "123456";
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"" + name + "\""+ lineEnd);
dos.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(value+ lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"upfile\"; 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)
int serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("upfile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
// close streams
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex)
{
Log.e("Debug", "erro: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.e("Debug", "erro: " + ioe.getMessage(), ioe);
}
And this is my php relevant code:
try {
if (
!isset($_FILES['upfile']['error']) ||
is_array($_FILES['upfile']['error'])
) {
throw new RuntimeException('Invalid parameters.');
}
switch ($_FILES['upfile']['error']) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
throw new RuntimeException('No file sent.');
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
throw new RuntimeException('Exceeded filesize limit.');
default:
throw new RuntimeException('Unknown errors.');
}
if ($_FILES['upfile']['size'] > 100000) {
throw new RuntimeException('Exceeded filesize limit.');
}
$variable = $_REQUEST["myvariable"];
//do what you want with the variable you send
if (!move_uploaded_file(
$_FILES['upfile']['tmp_name'],
sprintf('myfolder/%s',
$_FILES['upfile']['name']
)
)) {
throw new RuntimeException('Failed to move uploaded file.');
}
echo 'File is uploaded successfully.';
} catch (RuntimeException $e) {
echo $e->getMessage();
}

Posting file to https server with aspx?

This is my code to send file to server over HTTP,
but i am trying to transfer using HTTPS i tried it for passing values using parameters it was working but i don't know how to code it with file stream,
can anybody help me with this i have ssl certificate
void Sending() {
String iFileName = "video.mp4";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String Tag = "fSnd";
try {
Log.e(Tag, "Starting Http File Sending to URL");
// Open a HTTP connection to the URL
HttpURLConnection conn = (HttpURLConnection) connectURL
.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: form-data; name=\"title\""
+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(Title);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"description\""
+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(Description);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
+ iFileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.e(Tag, "Headers are written");
// create a buffer of maximum size
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
// read file and write it into form...
int 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);
// close streams
fileInputStream.close();
dos.flush();
Log.e(Tag,
"File Sent, Response: "
+ String.valueOf(conn.getResponseCode()));
InputStream is = conn.getInputStream();
// retrieve the response from server
int ch;
StringBuffer b = new StringBuffer();
while ((ch = is.read()) != -1) {
b.append((char) ch);
}
String s = b.toString();
Log.i("Response", s);
dos.close();
} catch (MalformedURLException ex) {
Log.e(Tag, "URL error: " + ex.getMessage(), ex);
}
catch (IOException ioe) {
Log.e(Tag, "IO error: " + ioe.getMessage(), ioe);
}
}

Why I get java.io.FileNotFoundException in getting the response to my httpUrlConnection?

I don't know if Im sending my file right to web api. Because nothing gives an error to client request code. But when I'm getting the response to the server it gives me a java.io.FileNotFoundException. So I think that there's wrong in my request code because it doesn't upload any file to the web server and I think that's why I get The java.io.FileNotFoundException. Please help me to this thanks.
HttpURLConnection conn = null;
DataOutputStream dos = null;
String samplefile = "storage/sdcard0/Pictures/Images/productshot.jpg";
String urlString = "http://avasd.server.com.ph:1217/api/fileupload";
File mFile = new File(samplefile);
int mychunkSize = 2048 * 1024;
final long size = mFile.length();
final long chunks = size < mychunkSize? 1: (mFile.length() / mychunkSize);
int chunkId = 0;
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 2 * 1024 * 1024;
try {
//Client Request
FileInputStream stream = new FileInputStream(mFile);
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "-------------------------acebdf13572468";// random data
String param1 = ""+chunkId;
String param2 = ""+chunks;
String param3 = mFile.getName();
String param4 = samplefile;
for (chunkId = 0; chunkId < chunks; chunkId++) {
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(20000 /* milliseconds */);
conn.setConnectTimeout(20000 /* milliseconds */);
// 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");
String encoded = Base64.encodeToString((_username+":"+_password).getBytes(),Base64.NO_WRAP);
conn.setRequestProperty("Authorization", "Basic "+encoded);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setChunkedStreamingMode(0);
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
int length = (int) (param2.length() + param3.length() + mFile.length() + encoded.length() + lineEnd.length() + twoHyphens.length() + boundary.length());
conn.connect();
dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(twoHyphens + boundary + lineEnd);
// Send parameter #file
dos.writeBytes("Content-Disposition: form-data; name=\"fieldNameHere\";filename=\"" + mFile.getName() + "\"" + lineEnd); // filename is the Name of the File to be uploaded
dos.writeBytes("Content-Type: image/jpeg" + lineEnd);
dos.writeBytes(lineEnd);
// Send parameter #chunks
dos.writeBytes("Content-Disposition: form-data; name=\"chunk\"" + lineEnd);
dos.writeBytes(param2 + lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
// Send parameter #name
dos.writeBytes("Content-Disposition: form-data; name=\"name\"" + lineEnd);
dos.writeBytes(param3 + lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
bytesAvailable = stream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = stream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = stream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = stream.read(buffer, 0, bufferSize);
Log.i("BytesAvailable", String.valueOf(bytesAvailable));
Log.i("bufferSize", String.valueOf(bufferSize));
Log.i("Bytes Read", String.valueOf(bytesRead));
Log.i("buffer", String.valueOf(buffer));
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
stream.close();
dos.flush();
dos.close();
Log.i("DOS: ", String.valueOf(dos.size()));
}
} catch (MalformedURLException ex) {
System.out.println("From CLIENT REQUEST:" + ex);
}catch (IOException ioe) {
System.out.println("From CLIENT REQUEST:" + ioe);
}catch (Exception e) {
Log.e("From CLIENT REQUEST:", e.toString());
}
//Server Response
try {
System.out.println("Server response is: \n");
DataInputStream inStream = new DataInputStream(conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null) {
System.out.println(str);
System.out.println("");
}
inStream.close();
System.out.println("\nEND Server response ");
} catch (IOException ioex) {
System.out.println("From (ServerResponse): " + ioex);
}
I think before you write data into file, you must make sure that the File variable's parent is available.You can see code below:
/**
*
* #param path
* like '/abc/temp' which will retutn '/mnt/sdcard/abc/temp'
* #return
*/
public static File getFile(String path) {
File file = new File(Environment.getExternalStorageDirectory() + path);
File parent = file.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return file;
}
This is a function which I often use.Hope it will help.
check permission in your manifest.xml
you should add permission to access sdcard0 memory location :
try this

Android Image Sharing to ImageShack Site

I am developing a android app. In this app need to upload image to imageShack site using their api.
Here "sourceFileUri" is image file path which come from sdcard of the device.It shows Outh or dev Key is invalid.. Please can anyone help me to find out the error. Advanced Thanks.
private void goForUpload(final String sourceFileUri)
{
if (!SharedPreferencesHelper.isOnline(con))
{
return;
}
pDialog = ProgressDialog.show(this, "Please wait...", "Loading...",false, false);
final Thread d = new Thread(new Runnable()
{
#Override
public void run() {
String upLoadServerUri = " http://www.imageshack.us/upload_api.php";
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
Log.w("file name are...", "" + sourceFile);
if (!sourceFile.isFile()) {
Log.e("uploadFile", "Source File Does not exist");
}
try { // open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
conn = (HttpURLConnection) url.openConnection(); // Open a
// HTTP
// connection
// to
// the
// URL
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);
// ///////////////////////////////////////////////////////////////////
//for image
dos.writeBytes("Content-Disposition: form-data; name=\"fileupload\";filename=\""+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"key\""+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes("289DGHSTbbfb01094c0017d23e96fe1edecda161");
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
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();
InputStream servere = conn.getInputStream();
String uyy = HttpRequest.GetText(servere);
System.out.print(uyy);
Log.w("uyy", "" + uyy);
Log.i("uploadFile", "HTTP Response is : "+ serverResponseMessage + ": " + serverResponseCode);
if (serverResponseCode == 200)
{
runOnUiThread(new Runnable()
{
public void run()
{
Toast.makeText(MainActivity.this,"File Upload Complete.",Toast.LENGTH_SHORT).show();
}
});
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
// Log.w("url", ""+url);
// final String url =
// "http://www.imageshack.us/upload_api.php?fileupload=http://www.libpng.org/pub/png/img_png/pnglogo-blk.jpg&url="+fos+"&optsize=100x100&rembar=yes&key=DHKNPRWYb185051e16c4545d8f26828d6fd3886c";
// final String url =
// "https://api.mobypicture.com/2.0/upload.json";//key=Az7IN9Qaxu3eZeK5/media=http://www.libpng.org/pub/png/img_png/pnglogo-blk.jpg/message=wasir";
//
// final String result = HttpRequest.GetText(HttpRequest
// .getInputStreamForGetRequest(url));
//
// try {
// if (parser.connect(con, result)) {
// Log.d("What is result :", result);
// }
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* update the GUI
*/
runOnUiThread(new Runnable() {
#Override
public void run() {
if (pDialog != null) {
pDialog.cancel();
}
}
});
}
});
d.start();
}
First Issue is the order you have your form-data parts:
dos.writeBytes("Content-Disposition: form-data; name=\"key\""+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes("xxxxxxxxxxxxxxxxxx");
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
//for image
dos.writeBytes("Content-Disposition: form-data; name=\"fileupload\";filename=\""+ fileName + "\"" + lineEnd);
dos.writeBytes("Content-Type: image/jpeg" + lineEnd);
dos.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
dos.writeBytes(lineEnd);
//dos.writeBytes(twoHyphens + boundary + lineEnd);
Second issue (when I tried) was that image type was invalid, so I added the content-type as seen above. And you didn't need the boundary before writing the file contents.

Categories

Resources