I'm trying to upload a file to a django server from an android phone, and i'm getting a strange mimetype. My code utilizes the Asynchrnous HTTP request client, and I'm using the below code:
File file = new File(/*Get file*/)
RequestParams params = new RequestParams();
params.put("file", file);
getAsyncHttpClient().post(url, params, new JsonHttpResponseHandler() {
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
error.printStackTrace();
}
public void onSuccess(final JSONObject obj) {
Log.i(TAG, obj.toString());
}
});
The content-type I'm getting on the server from a django FileField is application/octet-stream. Is there anyway to get the real mimetype to be passed in? I have been researching on this for sometime.
I read these below links:
Uploading an image from Android (with Android Asynchronous Http Client) to rails server (with paperclip)
Android image file sent to php upload image file is application/octet-stream type and not image/jpeg?
Is there something else I should be passing into the Android Asynchronous Http Client?
Can't believe I didn't see this before.
http://loopj.com/android-async-http/doc/com/loopj/android/http/RequestParams.html
You can just do:
params.put("file", file, mimetype);
Related
I am trying to get make a post request in Android using AsyncHttpClient using this code:
JSONObject jsonParams=new JSONObject();
try {
jsonParams.put("email", email);
}
catch (Exception e){
}
try {
StringEntity entity = new StringEntity(jsonParams.toString());
AsyncHttpClient client = new AsyncHttpClient();
client.post(getApplicationContext(),URL,entity, "application/json", new AsyncHttpResponseHandler(){
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {}
});
I am trying to access this data sent in the post request in my Python server. However, whenever I do request.json in my Python server, I get 'None' as response.
I also tried request.get_json(force=True) but getting 404 error code.
I dont really know if the data is being sent by the client APP or I am making a mistake while trying to retrieve it at the server side. Please help me with this issue.
String content = new String(responseBody);
Log.e("SUCCESS_RESP",""+content);
I am trying to send a bitmap (image captured in camera - Android) to nodejs. I am using AsycnHttpClient for the same. I am able to successfully send query parameters. I did refer to some of the links where the files are being sent and received. I tried the same, however, I guess nodejs code needs to be different for a bitmap and file (not sure?!)
Please can you help?
Client side code:
private void storeImage(Bitmap bm){
AsyncHttpClient client = new AsyncHttpClient();
//Append the parameters in the Service URL
RequestParams rp = new RequestParams();
String SERVICE_URL_REG = SERVICE_URL + "uploadImage?userID=rhari008";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
ByteArrayInputStream bInput = new ByteArrayInputStream(data);
rp.put("image",bInput);
client.post(SERVICE_URL_REG, rp, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.d(TAG,"Successfully uploaded the image");
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.d(TAG,"Error in uploading the image");
}
});
}
Server side code to receive the parameter:
//Image upload
router.post('/uploadImage', function(req, res, next) {
console.log("Image upload reached for " + req.query.userID);
var file = req.files.image;
console.log("File received : ");
//console.log("Image path : "+req.files.image.path);
res.json({result:"success"});
});
Please make sure your NodeJS server supports multipart first.
Yes.. I was able to arrive at the solution finally. I encoded the bitmap on base64 to stringify the same. That was stored post the compression. I retrieved it based and decoded the same to bitmap. It worked.
Hello guys I'm new to restful service.
My friend created REST backend with Spring.
When I post this URL --> http://smartcar.tobaconsulting.com:9999/api/v1/login with postman or angularjs http.post, it's fine.
You guys can check it out in postman by including this body
{ "username":"alvin", "password":"alvin" }
and set content type to JSON (application/json).
But when I code to Android, why it's not working and return 500 error code.
My friend said that I'm not including header. I'm using loopj http library http://loopj.com/. Here is my android code
RequestParams params = new RequestParams();
params.put("username", username);
params.put("password", password);
AsyncHttpClient client = new AsyncHttpClient();
client.post("http://smartcar.tobaconsulting.com:9999/api/v1/login", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.d(TAG, String.format("status code: %d", statusCode));
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.d(TAG, String.format("status code: %d", statusCode));
}
});
Please help me guys. I trying to solve this problem for hours and haven't find any clue.
Thanks
i checked your URL no error in server response
Access-Control-Allow-Credentials →true
Access-Control-Allow-Methods →GET, POST, PUT, DELETE
Access-Control-Allow-Origin →chrome-extension://mkhojklkhkdaghjjfdnphfphiaiohkef
Access-Control-Expose-Headers →X-AUTH-TOKEN
Content-Length →0
Date →Thu, 07 Apr 2016 08:35:26 GMT
Server →Apache-Coyote/1.1
X-AUTH-TOKEN
→eyJ1c2VybmFtZSI6ImFsdmluIiwiZW1haWwiOiJhbHZpbkBhbHZpbi5jb20iLCJleHBpcmVzIjoxNDYwODgyMTI2MDc4LCJvd25lcmlkIjo2LCJteVJvbGVzIjpbIlVTRVIiLCJBRE1JTiJdfQ==.M9/71trIPbnXxCh7avSWBK42UDXUxWYXZrNOlHhO7iQ=
I would personally suggest using Volley lib for android, there is some useful method inside volley and google strongly recommended that
Transmitting Network Data Using Volley
I have a following image upload api which works fine.
CURL --user username:password -X POST -H 'Content-Disposition: filename=scarlett-judinna.jpg' --data-binary #'/Volumes/Work/tmp/Dummy Images/image.jpg' http://example.com/wp-json/wp/v2/media
Now i want to upload image from android using this api.
I have tried the following process.
params.put("image", new ByteArrayInputStream(byte_arr));
AsyncHttpClient client = new AsyncHttpClient();
client.setBasicAuth(username, password);
client.addHeader("Content-Disposition", "filename=" + fileName);
client.addHeader("Content-Type", "image/" + extension);
client.post("http://example.com/wp-json/wp/v2/media",
params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
prgDialog.hide();
Toast.makeText(getApplicationContext(), response,
Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(int statusCode, Throwable error,
String content) {
Toast.makeText(getApplicationContext(), statusCode,Toast.LENGTH_LONG).show();
}
});
This always goes to the onFailure method with statusCode 403
So what am i doing wrong?
status code 403 suggests that the request is forbidden.
Perhaps the folder you are uploading to the server doesn't have write permissions.
I am trying to upload an image to a PHP file on a server using the POST method. I have been trying to do this using LoopJ AndroidAsyncHttp with no success. The server also requires a basic auth username and password. So far, I have been able to successfully POST the regular data parameters (These are simple string key-valued pairs like: "name":"joe") and get a response from the server. However, as soon as I try to attach the image to the POST request, the request fails giving me the following errors:
Error Message: null
Error Cause: org.apache.http.client.NonRepeatableRequestException: Cannot retry request with a non-repeatable request entity
The code that I am using follows the examples given at http://loopj.com/android-async-http/ very closely. Here is the code that I am using:
RequestParams params = new RequestParams();
params.put("name",name);
String path = "/path/to/img";
File myFile = new File(path, "picture.png");
if( myFile.exists() ) {
try {
params.put("picture", myFile);
} catch(FileNotFoundException e) {
Log.d("App","Error Attaching Picture: " + e.toString());
}
} else {
Log.d("App","File DOES NOT exist");
}
String urlString = "url-to-server";
AsyncHttpClient client = new AsyncHttpClient();
client.setBasicAuth("User", "Pass");
client.post(urlString, params, new AsyncHttpResponseHandler(){
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
super.onSuccess(statusCode, headers, responseBody);
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
super.onFailure(statusCode, headers, responseBody, error);
Log.d("App","Upload Failed!");
Log.d("App","Error Message: " + error.getMessage());
Log.d("App", "Error Cause: " + error.getCause());
}
#Override
public void onStart() {
super.onStart();
}
});
So what am I doing wrong here?
I have also double checked and the file that I am reading to get the image does exist and it does have data in it, so I have ruled that out as a potential cause.
I have been struggling with this issue a little too long now.
Thanks in advance to anyone who can help!
This was a bug in the old 1.4.4 version of AsyncHTTPClient. It can be fixed by updating to the 1.4.8 version. In your build.gradle file under the dependencies section it should look like this:
compile 'com.loopj.android:android-async-http:1.4.8'