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'
Related
In my app I want to decode raw address into coordinates. I do it like that:
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
try {
params.add("geocode", URLEncoder.encode(charSequence.toString(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
client.post(getApplicationContext(), "https://geocode-maps.yandex.ru/1.x/", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.d("Yandex Geocode", "Success! Answer = " + new String(responseBody));
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.d("Yandex Geocode", "Failure :( Error = " + error.toString());
}
});
However, this request can't reach server.
failed to connect to geocode-maps.yandex.ru/213.180.204.122 (port 443) after 10000ms: isConnected failed: ECONNREFUSED (Connection refused)
Any suggestions why it't not working?
EDIT
It not working because yandex provides this api only for webapps and sites.
Found an ugly workaround for this. I'm loading a page in webview with this request url and getting raw text from response, from webview.
You can try with Android Geocoder. It is android native API.
A class for handling geocoding and reverse geocoding.
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 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'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);
}
}
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);