I am trying to upload a zip file to our server along with the params using UrlConnection. This is uploading the file but it is not sending the parameters.
Here is the code.
private static final String CRLF = "\r\n"; // Line separator required by multipart/form-data.
private static final String CHARSET_UTF_8 = "UTF-8";
private static final String TWO_HYPHENS = "--";
public static void uploadReport(String filePath) {
File binaryFile = new File(filePath);
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
String urlString = "https://mycompany.com/api/file/uad.json";
HttpsURLConnection connection = null;
DataOutputStream dataOutoutStream = null;
try {
URL url = new URL(urlString);
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Cache-Control", "no-cache");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
OutputStream output = connection.getOutputStream();
dataOutoutStream = new DataOutputStream(output);
// Send normal param.
writeParameter(dataOutoutStream, boundary, "app_name", "My App Name");
writeParameter(dataOutoutStream, boundary, "app_version", "2.04");
// Send binary file.
writeBinaryFile(output, dataOutoutStream, boundary, binaryFile);
// End of multipart/form-data.
dataOutoutStream.writeBytes("--" + boundary + "--" + CRLF);
Log.v(tag, "response code " + connection.getResponseCode());
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch(UnsupportedEncodingException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
} finally {
if (dataOutoutStream != null)
try {
dataOutoutStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here is the code for my writeParameter method
private static void writeParameter(DataOutputStream dataOutputStream, String boundary, String paramName, String paramValue) throws IOException {
dataOutputStream.writeBytes(TWO_HYPHENS + boundary + CRLF);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + paramName + "\"" + CRLF);
dataOutputStream.writeBytes("Content-Type: text/plain; charset=" + CHARSET_UTF_8 + CRLF);
dataOutputStream.writeBytes(CRLF);
dataOutputStream.writeBytes(paramValue + CRLF);
dataOutputStream.flush();
}
Here is the writeBinaryFile method
private static void writeBinaryFile(OutputStream output, DataOutputStream dataOutputStream, String boundary, File binaryFile) throws IOException {
dataOutputStream.writeBytes(TWO_HYPHENS + boundary + CRLF);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"" + CRLF);
dataOutputStream.writeBytes("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName()) + CRLF);
dataOutputStream.writeBytes("Content-Transfer-Encoding: binary" + CRLF);
dataOutputStream.writeBytes(CRLF);
dataOutputStream.flush();
InputStream input = null;
try {
input = new FileInputStream(binaryFile);
byte[] buffer = new byte[1024];
for (int length = 0; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
// Important! Output cannot be closed. Close of writer will close output as well.
output.flush();
} finally {
if (input != null)
input.close();
}
dataOutputStream.writeBytes(CRLF);
dataOutputStream.flush();
}
May I know what I might be doing wrong.
I did check the Stackoverflow posts here and here.
Related
public class UploadProfilePicActivity extends Activity implements View.OnClickListener {
ImageView imageView;
Button btnUploadPic;
Button btnskipUploadPic;
Button btnSaveNContinue;
private static int RESULT_LOAD_IMAGE = 1;
String imagepath = null;
ProgressDialog dialog = null;
String url_profilePic;
private int serverResponseCode;
String api = "http://192.168.2.17:8000/api/v1/";
String format = "/?format=json";
AlmabayDatabase almabayDatabase;
String encodedString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uploadprofilepic);
imageView = (ImageView) findViewById(R.id.imageView);
btnUploadPic = (Button) findViewById(R.id.btnUploadPic);
btnskipUploadPic = (Button) findViewById(R.id.btnSkipUploadPic);
btnSaveNContinue = (Button) findViewById(R.id.btnSaveNContinue);
btnUploadPic.setOnClickListener(this);
btnSaveNContinue.setOnClickListener(this);
url_profilePic = api + "user-media" + format;
almabayDatabase = new AlmabayDatabase(this);
}
#Override
public void onClick(View v) {
if (v == btnUploadPic) {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
} else if (v == btnSaveNContinue) {
dialog = ProgressDialog.show(UploadProfilePicActivity.this, "", "Uploading file...", true);
// messageText.setText("uploading started.....");
new Thread(new Runnable() {
public void run() {
Log.e("ImagePathTest", imagepath);
uploadFile(imagepath);
}
}).start();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
imagepath = getPath(selectedImageUri);
Bitmap bitmap = BitmapFactory.decodeFile(imagepath);
imageView.setImageBitmap(bitmap);
Log.e("Uploading", "Uploading File :" + imagepath);
}
}
public String getPath(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public int uploadFile(String imagepath) {
String fileName = imagepath;
Log.e("File Name", fileName);
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(fileName);
int pk = almabayDatabase.getUserID();
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :" + imagepath);
runOnUiThread(new Runnable() {
public void run() {
Log.e("Sourcefile", "File doesn't exist");
}
});
return 0;
} else {
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(url_profilePic);
// 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("name", fileName);
// conn.setRequestProperty("timeline_id", String.valueOf(pk));
dos = new DataOutputStream(conn.getOutputStream());
//Send Image
Log.e("Sending","Sending Image");
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"name\";filename=\"" + fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// add parameter timeline_id
String timeline_id = String.valueOf(pk);
Log.e("Sending","Sending PK");
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"timeline_id\"" + lineEnd);
dos.writeBytes(lineEnd);
// assign value
dos.writeBytes(timeline_id);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + 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();
Log.e("ResponseCode", String.valueOf(serverResponseCode));
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if (serverResponseCode == 200) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(UploadProfilePicActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
//messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(UploadProfilePicActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
// messageText.setText("Got Exception : see logcat ");
Toast.makeText(UploadProfilePicActivity.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file failed", "Exception : " + e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
} // End else block
}
}
In this code ,I am trying to send image to server alongwith timeline_id .timeline_id contains the value pk that is the primary key of the user stored in the database.I am not able to send image with timeline_id.I don't know where the actual problem is.Please help me to resolve the issue.
You can simple put the file part along with the text part using the class below.
String charset = "UTF-8";
String requestURL = BASE_URL + "userregistration";
MultipartUtility multipart = new MultipartUtility(requestURL, charset);
multipart.addFormField("username", userJid);
multipart.addFilePart("image", imageBitmap);//ima
String response = multipart.finish();
Log.d("SERVER REPLIED", response);
You can create an MultipartUtility class as follow-
public class MultipartUtility {
private final String boundary;
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;
/**
* This constructor initializes a new HTTP POST request with content type
* is set to multipart/form-data
*
* #param requestURL
* #param charset
* #throws IOException
*/
public MultipartUtility(String requestURL, String charset)
throws IOException {
this.charset = charset;
boundary = "===" + System.currentTimeMillis() + "===";
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
httpConn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
httpConn.setRequestProperty("api_key", "a05f9ece-cd34-11e4-afdc-1681e6b88ec1");
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
true);
}
/**
* Adds a form field to the request
*
* #param name field name
* #param value field value
*/
public void addFormField(String name, String value) {
writer.append("--").
append(boundary).
append(LINE_FEED).
append("Content-Disposition: form-data; name=\"").
append(name).append("\"").
append(LINE_FEED).
append("Content-Type: text/plain; charset=").
append(charset).append(
LINE_FEED);
writer.append(LINE_FEED);
writer.append(value).append(LINE_FEED);
writer.flush();
}
/**
* Adds a upload file section to the request
*
* #param fieldName name attribute in <input type="file" name="..." />
* #param fileBytes a File to be uploaded
* #throws IOException
*/
public void addFilePart(String fieldName, byte[] fileBytes)
throws IOException {
// String fileName = uploadFile.getName();
writer.append("--")
.append(boundary)
.append(LINE_FEED)
.append("Content-Disposition: form-data; name=\"")
.append(fieldName)
.append("\"; filename=\"")
.append("user.jpeg")
.append("\"")
.append(LINE_FEED)
.append("Content-Type: image/jpeg")
.append(LINE_FEED)
.append("Content-Transfer-Encoding: binary")
.append(LINE_FEED)
.append(LINE_FEED);
writer.flush();
ByteArrayInputStream inputStream = new ByteArrayInputStream(fileBytes);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
writer.append(LINE_FEED);
writer.flush();
}
/**
* Adds a header field to the request.
*
* #param name - name of the header field
* #param value - value of the header field
*/
public void addHeaderField(String name, String value) {
writer.append(name).append(": ").append(value).append(LINE_FEED);
writer.flush();
}
/**
* Completes the request and receives response from the server.
*
* #return a list of Strings as response in case the server returned
* status OK, otherwise an exception is thrown.
* #throws IOException
*/
public String finish() throws IOException {
writer.append(LINE_FEED).flush();
writer.append("--")
.append(boundary)
.append("--")
.append(LINE_FEED)
.close();
String data = "";
int status = httpConn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
data = data + line;
}
reader.close();
httpConn.disconnect();
} else {
throw new IOException("Server returned non-OK status: " + status);
}
return data.isEmpty() ? null : data;
}
}
I have fixed the issue.Just need to do the following changes in the uploadFile() method.Everything is working file now.
public int uploadFile(String imagepath) {
String fileName = imagepath;
Log.e("File Name", fileName);
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(fileName);
int pk = almabayDatabase.getUserID();
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :" + imagepath);
runOnUiThread(new Runnable() {
public void run() {
// messageText.setText("Source File not exist :"+ imagepath);
Log.e("Sourcefile", "File doesn't exist");
}
});
return 0;
} else {
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(url_profilePic);
// 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("url", fileName);
// conn.setRequestProperty("timeline_id", String.valueOf(pk));
dos = new DataOutputStream(conn.getOutputStream());
// add parameter timeline_id
String timeline_id = String.valueOf(pk);
Log.e("Sending", "Sending PK");
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"timeline_id\"" + lineEnd);
dos.writeBytes(lineEnd);
// assign value
dos.writeBytes(timeline_id);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
//Send Image
Log.e("Sending", "Sending Image");
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"url\";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();
Log.e("ResponseCode", String.valueOf(serverResponseCode));
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if (serverResponseCode == 200) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(UploadProfilePicActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
//messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(UploadProfilePicActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
// messageText.setText("Got Exception : see logcat ");
Toast.makeText(UploadProfilePicActivity.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file failed", "Exception : " + e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
} // End else block
}
Simply use the below method to send multiple files with json request...
mImagePath is the arraylist of image paths
// Method for sending files using multiparting......
public static String sendJsonWithFile(Activity mActivity, ArrayList<String> mImagePaths, String jsonString, String URL)
{
Log.e("json", jsonString);
String res = "";
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
boundary = "--" + boundary;
httppost.addHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
StringBody stringBody = new StringBody(jsonString);
reqEntity.addPart("formstring", stringBody);
for (int i = 0; i < mImagePaths.size(); i++)
{
String imagePath = mImagePaths.get(i);
if (mImagePaths != null && mImagePaths.size() > 0)
{
byte[] filebytes = FileUtils.readFileToByteArray(new File(imagePath));
ByteArrayBody filebodyImage = new ByteArrayBody(filebytes, "image");
Log.e("file path=", filebodyImage.toString());
reqEntity.addPart("image", filebodyImage);
}
}
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null)
{
res = EntityUtils.toString(resEntity);
System.out.println(res);
}
if (resEntity != null)
{
resEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
}
catch (UnsupportedEncodingException e)
{
res = "UnsupportedEncodingException";
e.printStackTrace();
}
catch (ClientProtocolException e)
{
res = "ClientProtocolException";
e.printStackTrace();
}
catch (FileNotFoundException e)
{
res = "FileNotFoundException";
e.printStackTrace();
}
catch (IOException e)
{
res = "IOException";
e.printStackTrace();
}
catch (Exception e)
{
res = "Exception";
e.printStackTrace();
}
return res;
}
i'm trying to send some data to a server. The server is waiting a json and an image. I tried with every example that i found but i couldn't send the data. Actually i'm sending the json params with a PrintWriter object, but it doesn't accept the image. I need to use HttpURLConnection not with the apache library. This is my piece of code working:
HttpURLConnection connection = null;
PrintWriter output = null;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
attachImage.compress(Bitmap.CompressFormat.PNG, 40, stream);
byte[] imageData = stream.toByteArray();
String imagebase64 = Base64.encodeToString(imageData, Base64.DEFAULT);
Log.d(tag, "POST to " + url);
try{
URL url = new URL(this.url);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestProperty(HTTP_CONTENT_TYPE, "application/json; charset=utf-8");
connection.setRequestProperty(HTTP_USER_AGENT, mUserAgent);
connection.setRequestProperty(HTTP_HEADER_ACCEPT, "application/json; charset=utf-8");
connection.connect();
output = new PrintWriter(connection.getOutputStream());
JSONObject jsonParam = new JSONObject();
jsonParam.put("oauth_token", params.get("oauth_token"));
jsonParam.put("rating", "1");
jsonParam.put("comments", "ASDASDASDASDASDASDAS");
Log.d(tag, jsonParam.toString());
output.print(jsonParam);
output.flush();
output.close();
Log.d(tag, connection.getResponseCode() + connection.getResponseMessage());
}catch(Exception e ){
}
When I try to send an image in json params, I receive an 500 internal error message.
Thanks!
Okay , as per my suggestion 2 ways to send image to server
use base 64 string
Direct upload to server
1.for base 64 go to below link
Android post Base64 String to PHP
2.for direct upload to server Please check below link
http://www.androidhive.info/2014/12/android-uploading-camera-image-video-to-server-with-progress-bar/
Happy coding !!
People! After a lot of day, i could upload an image to a server! I was reading this library, which is for a lot of uses. https://source.android.com/reference/com/android/tradefed/util/net/HttpMultipartPost.html
I downloaded the source code, and i took some clases to send an image. I send only bytes, which were encoded from ASCII. Thanks for the help!
Check this below code to send form data and zip file containing images or other any media files.
private class MultipartFormTask extends AsyncTask<String, Void, String> {
String getStringFromInputStream(HttpURLConnection conn) {
String strResponse = "";
try {
DataInputStream inStream = new DataInputStream(
conn.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(
inStream));
String line;
while ((line = br.readLine()) != null) {
strResponse += line;
}
br.close();
inStream.close();
} catch (IOException ioex) {
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
return strResponse;
}
void uploadJSONFeed(HttpURLConnection conn, DataOutputStream dos,
String lineEnd) {
String issue_details_key = "issue_details";
String issue_details_value = "Place your Jsondata HERE";
try {
dos.writeBytes("Content-Disposition: form-data; name=\""
+ issue_details_key + "\"" + lineEnd
+ "Content-Type: application/json" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(issue_details_value);
dos.writeBytes(lineEnd);
} catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
}
void uploadZipFile(HttpURLConnection conn, DataOutputStream dos,
String lineEnd) {
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
InputStream is = null;
try {
is = getAssets().open("Test.zip");
} catch (IOException ioe) {
// TODO Auto-generated catch block
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
String zip_file_name_key = "file_zip";
String upload_file_name = "test.zip";
dos.writeBytes("Content-Disposition: form-data; name=\""
+ zip_file_name_key + "\";filename=\""
+ upload_file_name + "\"" + lineEnd); // uploaded_file_name
// is the Name
// of the File
// to be
// uploaded
dos.writeBytes(lineEnd);
bytesAvailable = is.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = is.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = is.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = is.read(buffer, 0, bufferSize);
}
dos.writeBytes(lineEnd);
is.close();
} catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String urlString = "http://www.example.org/api/file.php";
try {
// ------------------ CLIENT REQUEST
// FileInputStream fileInputStream = new FileInputStream(new
// File(existingFileName) );
// 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);
uploadJSONFeed(conn, dos, lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
uploadZipFile(conn, dos, lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
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
String strResponse = getStringFromInputStream(conn);
return strResponse;
}
#Override
protected void onPostExecute(String result) {
// might want to change "executed" for the returned string passed
// into onPostExecute() but that is upto you
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG)
.show();
Log.e("Result:", result);
}
}
you can upload large jsonstring using buffer please use bellow code .
HttpsURLConnection connection = null;
OutputStream os = null;
InputStream is = null;
InputStreamReader isr = null;
try {
connection = (HttpsURLConnection) url.openConnection();
SSLContext contextSSL = SSLContext.getInstance("TLS");
contextSSL.init(null, new TrustManager[]{new DefaultTrustManager()}, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(contextSSL.getSocketFactory());
MySSLFactory(context.getSocketFactory()));
HttpsURLConnection.setDefaultHostnameVerifier(new MyHostnameVerifier());
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setChunkedStreamingMode(0);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Authorization", auth);
connection.setConnectTimeout(timeoutMillis);
OutputStream os ;
if (input != null && !input.isEmpty()) {
os = connection.getOutputStream();
InputStream stream = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8));
BufferedInputStream bis = new BufferedInputStream(stream, 8 * 1024);
byte[] buffer = new byte[8192];
int availableByte = 0;
while ((availableByte = bis.read(buffer)) != -1) {
os.write(buffer, 0, availableByte);
os.flush();
}
}
int responseCode = connection.getResponseCode();
HTTP 500 error code means a server-side error occured.
This has nothing to do with your code.
The server is having a bug, not your code.
The application is working good in lower than 4.4.2 version in android. when am running application in 4.4.2 version device application is very slow while getting/calling data from the web service.
Is anyone facing this kind problem? please help me if have solution for this.
following is my code to attachemnt uploading.
private class UploadAttachmentTask extends AsyncTask {
ProgressDialog dialog;
int result = 0;
#Override
protected void onPostExecute(Boolean res) {
super.onPostExecute(res);
if (!ApplicationData.isOffline())
dialog.dismiss();
updateData(result);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (!ApplicationData.isOffline()) {
dialog = new ProgressDialog(EvidenceDetailActivity.this);
dialog.setMessage("Uploading resource...");
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMax(100);
dialog.setProgress(0);
dialog.setCancelable(false);
dialog.show();
}
}
// posting image audio, video file to server
public int postMediaDataToServer(String evidenceId, File file) {
String fileName = service.createFileNameWithDate(file);
System.gc();
int result = postAttachmentToServer(fileName, file, evidenceId);
return result;
}
#SuppressWarnings("deprecation")
public int postAttachmentToServer(String fileName, File file,
String evidenceId) {
try {
System.gc();
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "----WebKitFormBoundarysNDKBMUFqqvzYWGh";
byte[] buffer;
try {
long fileSize = file.length();
int bufferSize = 1024 * 512;
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(CacheAPI.mediaURL());
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
//conn.setChunkedStreamingMode(bufferSize);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("X-Ecordia-Software", "ecordiApp");
List<Cookie> cookies = ApplicationData.getCookieStore()
.getCookies();
if (cookies.size() > 0)
conn.setRequestProperty("Cookie", cookies.get(0)
.getName() + "=" + cookies.get(0).getValue());
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(lineEnd + twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"EvidenceIdentifier\""
+ lineEnd + lineEnd);
dos.writeBytes(evidenceId + lineEnd);
dos.writeBytes(lineEnd + twoHyphens + boundary + lineEnd);
if (fileName.endsWith(".jpg")) {
dos.writeBytes("Content-Disposition: form-data; name=\"File0\"; filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes("Content-Type: image/jpeg" + lineEnd
+ lineEnd);
} else if (fileName.endsWith(".mp4")) {
dos.writeBytes("Content-Disposition: form-data; name=\"File0\"; filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes("Content-Type: video/mp4" + lineEnd
+ lineEnd);
} else if (fileName.endsWith(".3gp")) {
dos.writeBytes("Content-Disposition: form-data; name=\"File0\"; filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes("Content-Type: video/3gp" + lineEnd
+ lineEnd);
} else if (fileName.endsWith(".mov")) {
dos.writeBytes("Content-Disposition: form-data; name=\"File0\"; filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes("Content-Type: video/quicktime"
+ lineEnd + lineEnd);
} else if (fileName.endsWith(".wav")) {
dos.writeBytes("Content-Disposition: form-data; name=\"File0\"; filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes("Content-Type: audio/wav" + lineEnd
+ lineEnd);
}
buffer = new byte[bufferSize];
int bytesRead = 0;
long count = 0;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
dos.write(buffer, 0, bytesRead);
count = count + bufferSize;
publishProgress((int) ((count * 100) / fileSize));
}
dos.writeBytes(lineEnd + twoHyphens + boundary + twoHyphens
+ lineEnd);
fileInputStream.close();
dos.flush();
dos.close();
} catch (Exception e) {
e.printStackTrace();
LogService.appendLog(Log.getStackTraceString(e));
}
try {
inStream = new DataInputStream(conn.getInputStream());
#SuppressWarnings("unused")
String str;
while ((str = inStream.readLine()) != null) {
}
inStream.close();
conn.disconnect();
return 0;
} catch (Exception ioex) {
LogService.appendLog(Log.getStackTraceString(ioex));
return 2;
}
} catch (Exception e) {
LogService.appendLog(Log.getStackTraceString(e));
return 2;
} catch (OutOfMemoryError e) {
LogService.appendLog(Log.getStackTraceString(e));
return 1;
}
}
#Override
protected void onProgressUpdate(Integer... values) {
dialog.setProgress(values[0]);
}
#Override
protected Boolean doInBackground(File... params) {
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
if (!ApplicationData.isOffline()) {
try {
result = postMediaDataToServer(
mCurrentEvidence.getEvidenceIdentifier(), params[0]);
} catch (Exception e) {
e.printStackTrace();
}
} else if (isOfflineEvidence) {
List<OfflineEvidence> offlineEvidences;
if (ApplicationData.isAssessor()) {
offlineEvidences = LoginActivity.assessorOfflineEvidenceDataSource
.getAllOfflineEvidences(
ApplicationData.getCandidateName(),
ApplicationData.getApiPortfolioId());
} else {
offlineEvidences = offlineDataSource
.getAllOfflineEvidences(ApplicationData
.getApiPortfolioId());
}
if (evidenceDate != null) {
for (OfflineEvidence offlineEvidence : offlineEvidences) {
if (offlineEvidence.getDate().equals(evidenceDate)) {
service.storeMediaToDataBase(offlineEvidence,
params[0]);
}
}
}
}
return true;
}
}
I am trying to upload a file to a server via HTTP POST from my device. I have two method upload1 and upload2.
Upload1 uses the HttpPost class and it works, but with bigger files it throws out of memory exception.
Upload2 uses HttpURLConnection and it does not work. (I get BAD REQUEST message from the server.) I want upload2 to work, because it uses stream to send the data and throws no out of memory exception.
I looked at the packages in wireshark, the headers are seems to be the same, however the length with upload1 is 380, with upload2 is only 94. What could be the problem?
private void upload1(File file) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url + "?recname="
+ fileName);
// ///////////////////////////////////////
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "---------------------------This is the boundary";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
FileInputStream fin = new FileInputStream(file);
byte audioData[] = new byte[(int) file.length()];
fin.read(audioData);
fin.close();
// Send a binary file
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes("Content-Type: audio/mp4" + lineEnd);
dos.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
dos.writeBytes(lineEnd);
dos.write(audioData);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dos.flush();
dos.close();
ByteArrayInputStream content = new ByteArrayInputStream(
baos.toByteArray());
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(content);
entity.setContentLength(baos.toByteArray().length);
httppost.addHeader("Content-Type", "multipart/form-data; boundary="
+ boundary);
httppost.setEntity(entity);
// //////////////////////////////////
HttpResponse response = httpclient.execute(httppost);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
reader.close();
message = builder.toString();
System.out.println(message);
} catch (UnknownHostException e) {
message = "Error! Server is unreachable. Check you internet connection!";
} catch (Exception e) {
message = "error: " + e.toString();
}
}
/////////////////////////////////////////////////////////////////////////////////////////
private void upload2(File file) {
HttpURLConnection connection = null;
String pathToOurFile = file.getPath();
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "---------------------------This is the boundary";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
fileInputStream = new FileInputStream(new File(pathToOurFile));
URL server_url = new URL(url+ "?recname="
+ fileName);
connection = (HttpURLConnection) server_url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Enable POST method
connection.setRequestMethod("POST");
String bodyHeader = twoHyphens
+ boundary
+ lineEnd
+ "Content-Disposition: form-data; name=\"file\";filename=\""
+ fileName + "\"" + lineEnd + "Content-Type: audio/mp4"
+ lineEnd + "Content-Transfer-Encoding: binary" + lineEnd
+ lineEnd + twoHyphens + boundary + twoHyphens ;
byte[] bodyHeaderAray = bodyHeader.getBytes();
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("Expect", "100-continue");
// Content-Length
int bodyHeaderSize = (int) file.length() + bodyHeaderAray.length;
System.out.println("body header size: " + bodyHeaderSize);
// connection.setFixedLengthStreamingMode(bodyHeaderSize);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream
.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""
+ fileName + "\"");
outputStream.writeBytes(lineEnd);
outputStream.writeBytes("Content-Type: audio/mp4" + lineEnd);
outputStream.writeBytes("Content-Transfer-Encoding: binary"
+ 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);
fileInputStream.close();
outputStream.flush();
outputStream.close();
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
message = serverResponseMessage;
} catch (Exception ex) {
System.out.println(ex);
}
}
According to the Problems you are getting to upload the files. you should use Multipart mechanism to upload the files to server.
httpclient-4.1.jar
httpcore-4.1.jar
httpmime-4.1.jar
apache-mime4j-0.6.1.jar
For that you need to add couple of libraries into your project and use it for HTTP connection and file data.
private boolean uploadFile(File mFile) {
boolean success = true;
String filename = mFile.getName();
MultipartEntity data_to_send = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
try {
data_to_send.addPart(
"name",
new StringBody(
filename.substring(filename.lastIndexOf("/") + 1)));
data_to_send.addPart("fileData", new FileBody(mFile));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
String responseData = ConsumeWebService.sendRequest(data_to_send,
Global.BASE_URL + serviceUrl);
if (TextUtils.isEmpty(responseData)
|| responseData.equals(ConsumeWebService.ERROR_CODE)) {
success = false;
}
} catch (Exception e) {
success = false;
e.printStackTrace();
}
return success;
}
public static String sendRequest(MultipartEntity data, String url) {
String response = "";
response = postData(url, data);
return response;
}
private static String postData(String url, MultipartEntity data) {
String strResponse = "";
try {
Log.d(Global.TAG, "Post URL is " + url);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(data);
strResponse = httpClient.execute(httpPost,
new BasicResponseHandler());
} catch (UnsupportedEncodingException e) {
strResponse = ERROR_CODE;
e.printStackTrace();
} catch (ClientProtocolException e) {
strResponse = ERROR_CODE;
e.printStackTrace();
} catch (IOException e) {
strResponse = ERROR_CODE;
e.printStackTrace();
}
return strResponse;
}
You can build by your own your POST Request by following this w3.org docs about forms.
I think in upload2 you are missing one lineEnd where you do:
....
outputStream.writeBytes("Content-Transfer-Encoding: binary"
+ lineEnd);
After this, you have to transmit the data and it takes two lineEnds before actual data, so it should be:
....
outputStream.writeBytes("Content-Transfer-Encoding: binary"
+ lineEnd + lineEnd);
For reading files and place them in multipart/form-data structure, I suggest you this way that works for me:
FileInputStream fileInputStream=new FileInputStream(file);
byte[] bytes= new bytes[fileInputStream.getChannel().size()];
fileInputStream.read(bytes);
fileInputStream.close();
outputStream.write(bytes);
outputStream.writeBytes(lineEnd);
Hope it helps.
I am developing an android application in which i have to post some data to url.I did googling and got some samples.I tried them out.But i did not got the response as required.
Below is the link which i tried
http://www.androidsnippets.com/executing-a-http-post-request-with-httpclient
Has anyone done this before.If yes can he help me
Thanks in advance
Tushar
I create a class with all my information I need to send and serialize it to a xml file with simple xml. Then I send the entire XML.
But you can send fields only too:
static String CRLF = "\r\n";
static String twoHyphens = "--";
static String boundary = "*****mgd*****";
private DataOutputStream dataStream = null;
private void postData(){
try{
URL connectURL = new URL("http://example.com/upload.php");
HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("User-Agent", "test");
conn.setRequestProperty("Connection","Keep-Alive");
conn.setRequestProperty("Content-Type","multipart/form-data;boundary="+boundary);
conn.connect();
dataStream = new DataOutputStream(conn.getOutputStream());
//Send fields
writeFormField("name", "bla");
writeFormField("password", "bla");
//Send a file
File uploadFile = new File(SD_CARD_TEMP_DIR, "file.xml");
FileInputStream fileInputStream = new FileInputStream(uploadFile);
writeFileField("myFile", "somefilename.xml", "text/xml",fileInputStream);
// final closing boundary line
dataStream.writeBytes(twoHyphens + boundary +twoHyphens + CRLF);
fileInputStream.close();
dataStream.flush();
dataStream.close();
dataStream = null;
boolean response = getResponse(conn);
if(response)
{
finish();
}
}
catch (MalformedURLException mue) {
// TODO
}
catch (IOException ioe) {
// TODO
}
catch (Exception e) {
// TODO
}
}
private void writeFormField(String fieldName, String fieldValue) {
try {
dataStream.writeBytes(twoHyphens + boundary + CRLF);
dataStream.writeBytes("Content-Disposition: form-data;name=\"" + fieldName + "\"" + CRLF);
dataStream.writeBytes(CRLF);
dataStream.writeBytes(fieldValue);
dataStream.writeBytes(CRLF);
} catch (Exception e) {
System.out.println("writeFormField:got: " + e.getMessage());
}
}
private void writeFileField(
String fieldName,
String fieldValue,
String type,
FileInputStream fis)
{
try
{
// opening boundary line
dataStream.writeBytes(twoHyphens + boundary + CRLF);
dataStream.writeBytes("Content-Disposition: form-data; name=\""
+ fieldName
+ "\";filename=\""
+ fieldValue
+ "\""
+ CRLF);
dataStream.writeBytes("Content-Type: " + type + CRLF);
dataStream.writeBytes(CRLF);
// create a buffer of maximum size
int bytesAvailable = fis.available();
int maxBufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
// read file and write it into form...
int bytesRead = fis.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
dataStream.write(buffer, 0, bufferSize);
bytesAvailable = fis.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fis.read(buffer, 0, bufferSize);
}
// closing CRLF
dataStream.writeBytes(CRLF);
}
catch(Exception e)
{
Log.i(TAG, "writeFormField: got: " + e.getMessage());
}
}
private boolean getResponse(HttpURLConnection conn)
{
try {
// try doing this in one read
InputStream data = conn.getInputStream();
StringBuffer sb = new StringBuffer();
//Reader reader = new InputStreamReader(data, "UTF-8");
int c;
while ((c = data.read()) != -1) sb.append((char) c);
String document = sb.toString();
int responseCode = conn.getResponseCode();
return true;
}
catch(Exception e)
{
}
return false;
}