GET doesn't enter in methods onSucces and onFailure - android

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

Related

send data in raw using asynhttpclient

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

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

why AsyncHttpClient method calls both onSuccess and onFailure method simultaneously

I don't understand why both the methods are called simultaneously ie onSuccess and onFailure method of AsyncHttpClient. Here is the following code snippet.
AsyncHttpClient client = new AsyncHttpClient();
client.post(context, url, entity, "application/json", new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject obj)
{
System.out.print("Inside success method....");
try
{
System.out.println("Inside try of success method");
if ("SUCCESS".equals(obj.getString("status")))
{
System.out.println("Status : " + obj.getString("status"));
statusFlag = statusFlag+1;
System.out.println("Double Status Flag: "+statusFlag);
}
else
{
//statusFlag = 2;
}
}
catch (JSONException e)
{
//statusFlag = 3;
}
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse)
{
if (statusCode == 404)
{
//statusFlag = 4;
}
else if (statusCode == 500)
{
//statusFlag = 5;
}
else
{
//statusFlag = 6;
}
}
});

Upload of Large File Using AndroidAsyncHttp Fails after sometime from android

I am trying to upload a file using AsyncHttpClient.Below is the code :
public class uploadVideoAsyncTask extends AsyncTask<String,Void,JSONObject>{
Context context;
SyncHttpClient client;
JSONObject response;
public uploadVideoAsyncTask(Context context) {
this.context = context;
}
#Override
protected JSONObject doInBackground(String... params) {
if(client != null){
RequestParams data = new RequestParams();
File video = new File(params[0]);
try {
data.put("upload", video, "video/*");
Log.d("debug", LoginActivity.URL + LoginActivity.URL_UPLOAD_VIDEO);
client.post(LoginActivity.URL+LoginActivity.URL_UPLOAD_VIDEO,data,new JsonHttpResponseHandler(){
#Override
public void onProgress(long bytesWritten, long totalSize) {
super.onProgress(bytesWritten, totalSize);
Log.d("debug",bytesWritten +" "+ totalSize);
}
#Override
public void onUserException(Throwable error) {
super.onUserException(error);
Log.d("debug",error.toString());
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
Log.d("debug", response.toString());
initializeResponse(response);
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
Log.d("debug", errorResponse.toString());
initializeResponse(errorResponse);
}
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Log.d("debug", responseString);
initializeResponse(null);
}
});
} catch (FileNotFoundException e) {
e.printStackTrace();
initializeResponse(null);
}
}else{
initializeResponse(null);
}
return this.response;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
initializeHttpClient();
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
Log.d("debug","ererr");
}
private void initializeResponse(JSONObject response){
this.response = response;
}
private void initializeHttpClient(){
if(client == null){
client = new SyncHttpClient();
//client.setMaxRetriesAndTimeout(LoginActivity.maxRetries, LoginActivity.TIME_OUT);
client.setTimeout(50000);
Log.d("debug", client.getResponseTimeout() + "");
Log.d("debug", client.getConnectTimeout()+"");
client.addHeader("x-access-token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiI1NzFiOTBmOTM4ZmQ1NzA4MGUzMTY1Y2IifQ.2l4DVRTVhxFnD796M5CPIEloGW6N-qBnXxa3lC0XDRU");
//client.addHeader("Content-Type", " application/json");
}
}
}
this code works fine if the file upload takes very less time approx 1 min, But if the file size is greater and take more time . The AsyncHttpclient stops uploading File after some time without any error.
I have already tried with different setTimeOut .
Also there Is no error on server side. with Advanced rest client i have i am able to load any file size.
Thanks
Set
RequestParams data = new RequestParams();
if (file != null && file.exists())
data.put("Db_file", new FileInputStream(file));
data.setForceMultipartEntityContentType(true);
RequestParams class creates a non-buffered ByteArrayEntity to pass to the POST or PUT call, it is very easy to cause OutOfMemory errors with larger files, like when uploading a video or mp3 to a server, which are often larger than 4 or 5 MB.

CANNOT POST , can't reach nodejs from android

I can't reach my nodejs server from an androiapp endpoint.
The thing is that I can reach from others post, but not from a new one.
From this url I can reach:
ApiClient.post("/v1/forgot", params,
new AsyncHttpResponseHandler() {
#Override
public void onFailure(int arg0, Header[] arg1,
byte[] arg2, Throwable arg3) {
userMessage=("Password NOT RESET.\n Please check the email entered,\n"+userEmailEntered+"\nor try again later.");
Toast.makeText(getApplicationContext(), userMessage, Toast.LENGTH_LONG).show();
}
#Override
public void onSuccess(int arg0, Header[] arg1,
byte[] resp) {
String response = new String(resp);
try {
JSONArray jsonArray=new JSONArray(response);
String json = jsonArray.getJSONObject(0).toString();
final ResetPasswordResponse resetPasswordResponse = JsonUtils.parseJson(json, ResetPasswordResponse.class);
if (resetPasswordResponse.getStatus().equals("sent")){
userMessage=("Reset instructions sent to "+resetPasswordResponse.getEmail());
}else{
userMessage=("The email account entered "+resetPasswordResponse.getEmail()+" is not recognized. Please check the email address entered");
}
Toast.makeText(getApplicationContext(), userMessage, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
But I can't from the new resource and post that Im creating:
Log.i("store", devRegId.toString());
//TODO PROBLEM TO SEND REGISTRATION - cannot post
ApiClient.post("/v1/device", params,new AsyncHttpResponseHandler(){
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] resp) {
String response = new String(resp);
Log.i("store", response);
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] resp, Throwable error) {
Log.i("store", "NOT ok");
Log.i("store", resp.toString());
String response = new String(resp);
Log.i("store", response);
}
});
And that it`s the client.post created:
private static AsyncHttpClient client = new AsyncHttpClient();
public static void post(String url, RequestParamsCustom params, AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
}
Server route:
app.post('/v1/device', function(req,res) {
gcmDeviceRouter.storeDevice(req,res)
});
The server is running ok, I can access from other end point (web app, postman tool).
The error it`s this:
debug I/store﹕ NOT ok
debug I/store﹕ [B#235ae686
debug I/store﹕ Cannot POST /v1/device
Thanks for the help

Categories

Resources