send data in raw using asynhttpclient - android

I m posting JSON in raw with this Url [URL I post data to][1]
param is=eventName="countryList"
codes
private void testApp() {
try {
JSONObject jsonParams = new JSONObject();
jsonParams.put("key", "value");
StringEntity entity = new StringEntity(new Gson().toJson(jsonParams));
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
AsyncHttpClient client = new AsyncHttpClient();
client.post(getApplicationContext(), "url", entity, "application/json", new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
super.onSuccess(statusCode, headers, response);
Log.e("good",response.toString());
}
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Log.e("fail",throwable.toString());
}
});
} catch (Exception e) {
}
}
error:fail: cz.msebera.android.httpclient.client.HttpResponseException: Internal Server Error

change fromStringEntity entity = new StringEntity(new Gson().toJson(jsonParams));
to:**StringEntity stringEntity = new StringEntity(jsonParams.toString());**
And Also override
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
}
your response return jsonobject not array

Related

GET doesn't enter in methods onSucces and onFailure

I'm trying to do a get with AsyncHttpClient, but doesn't enter in both methods, in Postman it's going well, any idea what could be?
AsyncHttpClient client = new AsyncHttpClient();
String URL = "http://link/link1/link2";
client.get(URL, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
JSONArray dni;
String strResponseBody = new String(responseBody);
try {
dni = new JSONArray(strResponseBody);
for(int i=0; i < dni.length(); i ++){
dniTemporal = dni.getString(i);
Log.d("DNI : ",""+ dniTemporal );
}
} catch (JSONException e) {
Toast.makeText(JourneyDetails.this, "Error", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.d("ERROR STATUS:"," "+ statusCode);
}
});

Upload image with loopj android to slim framework based REST api?

I am trying to upload image using Params.
Android code:
POST Data to Server
RequestParams params = new RequestParams();
params.put("item_name", "Name of item");
params.put("item_image", encodedImage);
MyRestClient.post(MainActivity.this, "item",params, new JsonHttpResponseHandler(){
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
JSONArray jArr = response;
super.onSuccess(statusCode, headers, response);
}
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
String responseFromAPI = responseString;
super.onFailure(statusCode, headers, responseString, throwable);
}
#Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
String responseStr = responseString;
super.onSuccess(statusCode, headers, responseString);
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
JSONObject jObj = response;
super.onSuccess(statusCode, headers, response);
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
JSONObject jOBj = errorResponse;
super.onFailure(statusCode, headers, throwable, errorResponse);
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
JSONArray jArr = errorResponse;
super.onFailure(statusCode, headers, throwable, errorResponse);
}
});
Bitmap Image Encode
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
Slim Framework Code:
$app->post('/image', function ($request, $response) {
$input = $request->getParsedBody();
$uploaded_image = $input['image_image'];
$path = "/..../uploads/"."img-".date("Y-m-d-H-m-s").".jpg";
if (file_put_contents($path, base64_decode($uploaded_image)) != false)
{
$sql = "INSERT INTO item (item_name, item_image) VALUES (:restaurant_name, :restaurant_image)";
$sth = $this->db->prepare($sql);
$sth->bindParam("item_name", $input['item_name']);
$sth->bindParam("item_image", $input['item_image']);
$sth->execute();
$input['id'] = $this->db->lastInsertId();
}
return $this->response->withJson($input);
});
Problem:
The photo should be uploaded as per the code and my understanding. It is not uploading the image to the desired folder.
Am I doing things correctly or have I missed something?
<?php
$app->post('/image', function ($request, $response) {
$files = $request->getUploadedFiles();
$file = $files['image_image']; // uploaded file
$parameters = $request->getParams(); // Other POST params
$path = "/..../uploads/"."img-".date("Y-m-d-H-m-s").".jpg";
if ($file->getError() === UPLOAD_ERR_OK) {
$file->moveTo($path); // Save file
// DB interactions here...
$sql = "INSERT INTO item (item_name, item_image) VALUES (:restaurant_name, :restaurant_image)";
$sth = $this->db->prepare($sql);
$sth->bindParam("item_name", $input['item_name']);
$sth->bindParam("item_image", $input['item_image']);
// if statement is executed successfully, return id of the last inserted restaraunt
if ($sth->execute()) {
return $response->withJson($this->db->lastInsertId());
} else {
// else throw exception - Slim will return 500 error
throw new \Exception('Failed to persist restaraunt');
}
} else {
throw new \Exception('File upload error');
}
});

GZipped content in http response of GET request using async-http-library for Android

I'm trying to access Google's geocode API using Android-Async-http library in my app. Here is my request and below is response:
���������������UMo�0��WX>Ӫ i{���UJ�$�J�
mߔ%�===�������B��R��}���#�4�.�d�{��$�b��D��V<��<�����w*y�q���y5����o� �����
Here is success callback method of AsyncHttpResponseHandler.
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
if (statusCode == HttpStatus.SC_OK) {
try {
String response = new String(responseBody);
//String response = new String(responseBody, "UTF-8"); //this is also giving junk reponse
Log.v("SUCCESS RESPONSE", response);
networkCallback.onSuccess(response);
}catch (Exception e){
e.printStackTrace();
}
}
}
Why am i getting the response as junk? How do I get proper response?
Try this :
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
MyLog.log(TAG, response.toString());
// if is Jsonobjec
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
super.onSuccess(statusCode, headers, response);
MyLog.log(TAG, response.toString());
// if is JsonArray
}
Or you want get response string:
#Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
super.onSuccess(statusCode, headers, responseString);
}
Used
compile 'com.loopj.android:android-async-http:1.4.9'
instead of 1.4.5

android - GET-request with Loopj

I need to make GET-request to a url consisting JSON-data and try to use Loopj library, but it returnes nothing. I tried to find examples on the Internet but they turned out, maybe, to be obsolete (onSuccess method had different parameters). I tried to adapt my code to that example and what I got:
String AllData=""; AsyncHttpClient client = new AsyncHttpClient();
client.get("wantedUrl", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
for (byte aResponseBody : responseBody) {
AllData += aResponseBody;
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Toast.makeText(getApplicationContext(),"We got an error",Toast.LENGTH_SHORT).show();
}
});
"wantedUrl" is the url with json, but "AllData" remains empty. How to fix it?
You're getting AsyncHttpResponseHandler callback where you're in need of JsonHttpResponseHandler. Use below code to get the things right on track.
String AllData=""; AsyncHttpClient client = new AsyncHttpClient();
client.get("wantedUrl", new JsonHttpResponseHandler(){
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
super.onSuccess(statusCode, headers, response);
//Here response will be received in form of JSONArray
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
//Here response will be received in form of JSONObject
}
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Toast.makeText(getApplicationContext(), "We got an error", Toast.LENGTH_SHORT).show();
}
});

LoopJ AndroidAsyncHttp is returning response in OnFailure

i am new to AndroidAsyncHttp.
i created a class httptester :
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(getAbsoluteUrl(url), params, responseHandler);
}
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return relativeUrl;
}
and in my activity did the following:
RequestParams params = new RequestParams();
params.put("FTID", HTTPRequestUserAuthentication.AppID);
params.put("UUID", MainActivity.uuid);
params.put("TYPE", "11");
params.put("DateTimeStamp", DateTimeStamp);
params.put("SDFVersionNb", SDFVersionNb);
httptester.post(MainActivitySharedPref.GetValue(MyApplication.getContext(), "WebService_URL")+MyApplication.getContext().getResources().getString(R.string.url_get_user_data), params,new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
super.onSuccess(statusCode, headers, responseString);
Log.e(TAG, "sucess: " + responseString);
}
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
Log.e(TAG, "failure: " + responseString);
Log.e(TAG, "failurecode: " + statusCode);
super.onFailure(statusCode, headers, responseString, throwable);
}
});
after calling the client, the correct response is being returned but it is being returned in OnFailure and not in OnSuccess. i also printed the status code in onfailure and it is 200 which supposedly should be OK.
any help would be appreciated.
So you call in your request
new JsonHttpResponseHandler()
But you need
new AsyncHttpResponseHandler()

Categories

Resources