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);
Related
I'm new to Android, I'm using AsyncHttpClient to call a POST API. But the API is not even being called
Below is my code:
AsyncHttpClient client = new AsyncHttpClient();
client.addHeader("Key","random-key");
JSONObject body = new JSONObject();
body.put("clientId","random-client-id");
body.put("question",question);
HttpEntity entity = new StringEntity(body.toString());
client.post( getApplicationContext(),"http://localhost:3000/api/Chats/GetAnswer", entity,"application/json", new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
List<List<Answer>> answers = new ArrayList<>();
try {
JSONArray answersJson = response.getJSONArray("answers");
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, String response, Throwable error) {
Toast toast = Toast.makeText(getApplicationContext(),"Unable to get answers for the question sent",Toast.LENGTH_SHORT);
toast.show();
}
});
`
Any hints of what I'm doing wrong??
Solved, it appear that the problem was in AndroidManifest.xml Since I'm using the internet and calling an external API, I had to add:
<uses-permission android:name="android.permission.INTERNET"/>
And another thing. When working locally and testing using the emulator, we should write
http://10.0.2.2:port-number/ instead of http://localhost:port-number/. Because android emulator runs in a virtual machine. Therefore, localhost will be emulator's own loopback address.
Please put debugger at your method and Make sure its calling or not , I think you have passed wrong context value And as my point of View its better to User Retrofit than AsyncHttpClient.
Use Retrofit if you are communicating with a Web service.
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 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'
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 using LoopJ AndroidAsyncHttp to post async Http calls from my android app. When i specify some RequestParams, the call keep failing, with a statusCode 415(Unsupported Media Type). As soon as i remove the requestParams the call goes through, without any error.
final AsyncHttpClient client;
String url = "http://someURL.com/SomeUserGUID/Profile/Statistics/Setup";
client = new AsyncHttpClient();
final RequestParams params = new RequestParams();
params.put("FirstClub", "false");
params.put("FairwayHit", "false");
Header[] headers = {
new BasicHeader("Accept-Language", Locale.getDefault().toString())
,new BasicHeader("Authorization", ApplicationObject.companyBasicAuthString)
,new BasicHeader("Accept", "application/json")
};
client.setTimeout(60000);
client.post( ProfileActivity.this,url, headers, params, "application/json", new AsyncHttpResponseHandler() {
#Override
public void onStart() {
//Do something before start
super.onStart();
}
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
//some code
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
//some code
}
});
My goal is for the URL to look like this: String url = http://someURL.com/SomeUserGUID/Profile/Statistics/Setup?FirstClub=false& FairwayHit=false
I would pref not to hard code the URL into one single string(This method works btw), because i have some calls that would create a really long URL string.
So how can i achieve a successful post call, with params, using AndroidAsyncHttp?
415 Unsupported Media Type
The server is refusing to service the request because the entity of the request is in a format not supported
by the requested resource for the requested method.
You're sending the Content-Type header (in your post call) as "application/json", but the params you've added are not JSON. This is probably why the error occurs.