uploading image from android through WP REST API - android

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.

Related

RESTful web service error 500 on android

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

LoopJ AndroidAsyncHttp Can't POST Image With Basic Auth

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'

Uploading an image from Android (with Android Asynchronous Http Client) to laravel server

i'm trying to upload an image via http post method from android device to laravel server. but Posting an image is not working, the post parameter (including image file) doesn't seem to be sent correctly.
i'm using Android Asynchronous Http Client (http://loopj.com/android-async-http/) to post an image from android. and here is the code :
Android :
RequestParams params = new RequestParams();
params.put("id_personil", session.getUID());
params.put("id_deskel", session.getDID());
params.put("jenis", jenisLap.getSelectedItemPosition());
params.put("judul", judul.getText().toString());
params.put("lokasi", lokasi.getText().toString());
params.put("uraian", uraian.getText().toString());
try{
for (int a =0; a<imageUrl.size();a++){
params.put("pic[]", new File(Environment.getExternalStorageDirectory().getPath()+imageUrl.get(0)));
}
}catch(FileNotFoundException e){e.printStackTrace();}
AsyncHttpClient client = new AsyncHttpClient();
client.post("http://10.0.3.2:8888/api/v1/lapgiat", params, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
ShowAlert(response.toString(), "text");
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
ShowAlert("Error", "error");
}
});
Laravel
if(Request::has('pic')){
$files = Input::file('pic');
//dd($files);
$det_pic = [];
foreach ($files as $file) {
$filename = rand(11111,99999).'.'.$file->getClientOriginalExtension();
$file->move('uploads', $filename);
$det_pic[] = ['id_lapgiat'=>$id, 'file'=>$filename];
}
DB::table('bah_det_lapgiat_photo')->insert($det_pic);
$output['has picture'] = true;
}
can anyone help me?
Check using cURL or POSTMAN client and see if it's working there. If not, you can use this sample code for laravel.
//Checks if request has file or not
if ($request->hasFile('pic')) {
//checks if file is uploaded or not
if ($request->file('pic')->isValid()) {
$extension = $request->file('pic')->getClientOriginalExtension();
$imageName = str_random(60);
$request->file('pic')->move(base_path() . 'file/save/location', $imageName.".".$extension);
}
}

Mimetype of file uploaded to django

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);

Response string is blank in loopj for Android

Here is the code that I have used for Async Http requests using loopj.
AsyncHttpClient loopjClient = new AsyncHttpClient();
PersistentCookieStore loopjCookieStore = new PersistentCookieStore(this);
loopjClient.setCookieStore(loopjCookieStore);
RequestParams loopjParams = new RequestParams();
loopjParams.put("username", username);
loopjParams.put("email", emailID);
loopjParams.put("password", password);
Log.d(TAG, "RRRRRRlll");
loopjClient.post("http://www.example.com/", loopjParams, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int k,String response) {
super.onSuccess(k, response);
Log.d(TAG, "RRRRRR "+ response );
}
});
And my server response string is just the following with out the HTML tags
{"AUTHENTICATION":{"SUCCESS":false,"USERNAME":"unregistered","USERID":0},"ALERTBOX":{"SHOW":true,"MESSAGE":"Message : Username or email ID already registered. Please choose a different one."}}
But loopj doesnt print the above string in onSuccess().
Can you tell how to get the string or do I have to fall back to default Android http library ?
Thanks in advance.
EDIT
Instead of 'example'(my site) if I replace it with 'facebook' I just get the following string as response with a 200 response code <?xml version="1.0" encoding="utf-8"?>
Since the result of AUTHENTICATION failed, I'm wondering if the status code that your server return is not 200. You can override onFailure method to deal with this situation.
#Override
public void onFailure(Throwable e) {
Log.d(TAG, e.toString());
}
Edit
Another guess, have you added the following line in your Manifest.xml?
<uses-permission android:name="android.permission.INTERNET" />
Edit Again
I saw your edit, and it seems that you have an buggy LogCat as #shailendra-rajawat mentioned in comment, since LogCat printed only the first line. Try Toast instead:
#Override
public void onSuccess(int k, String response) {
Toast.makeText(getBaseContext(), response, 1).show();
}
I found this post for configuring your LogCat, and maybe you can give it a try. (Mine is 5000 FYI)

Categories

Resources