I am using android-async-http to run a simple push notification example.
The device is able to receive the notification just fine. After it receives the file, I am calling a get request using the above mentioned library:
Log.d("TAG", "GOT");
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://mysafeinfo.com/api/data?list=states&format=json", new AsyncHttpResponseHandler() {
#Override
public void onStart() {
// called before request is started
}
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// called when response HTTP status is "200 OK"
try {
String decoded = new String(response, "UTF-8");
Log.d("TAG", decoded);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
try {
String dec = new String(errorResponse, "UTF-8");
Log.d("TAG",dec);
}
catch (UnsupportedEncodingException q){
q.printStackTrace();
}
}
#Override
public void onRetry(int retryNo) {
// called when request is retried
}
});
In that url should return json, but in my log, I see no messages at all. its all blank, that log.d is never called. But when I change that url to www.google.com, it returns some html (which is google's homepage) .
I have added
<uses-permission android:name="android.permission.INTERNET" />
to the manifest.
This is my logcat:
02-13 21:06:12.189
12101-12101/com.example.harshvardhangupta.gcmpleasework D/TAG: GOT
02-13 21:06:12.468
12101-12101/com.example.harshvardhangupta.gcmpleasework V/AsyncHttpRH:
Progress 1310 from 1522 (86%) 02-13 21:06:12.468
12101-12101/com.example.harshvardhangupta.gcmpleasework V/AsyncHttpRH:
Progress 3333 from 1522 (219%) 02-13 21:06:12.469
12101-12101/com.example.harshvardhangupta.gcmpleasework V/AsyncHttpRH:
Progress 5238 from 1522 (344%)
Do notice the dotted lines. After #Taylor Courtney's comment, I noticed that the response is coming , but its not being converted to a string from byte array properly
Well, Your AsyncHttpClient (doc) is requesting link which is returning JsonArray (response). You should use then JsonHttpResponseHandler (doc) instead.
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://mysafeinfo.com/api/data?list=states&format=json", new JsonHttpResponseHandler("UTF-8") {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
super.onSuccess(statusCode, headers, response);
Log.d(TAG, "onSuccess response: " + response.toString());
}
}
});
Related
I am using loopj library for http request, And i am using genymotion for testing. I also want to test on my mobile device but it is showing host unreachable on each ip, whenever i call onclick function on button click.
Here is the Code:
public void onClick(View view) {
username = emailET.getText().toString();
password = pwdET.getText().toString();
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("username", username);
params.put("password", password);
client.post("http://10.0.3.2:3000/index", params, new TextHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, String res) {
try {
JSONObject obj = new JSONObject(res);
if(obj.getString("success").equals("true")){
Toast.makeText(getApplicationContext(),"Service connected", Toast.LENGTH_LONG);
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Server not connected",Toast.LENGTH_LONG);
}
// called when response HTTP status is "200 OK"
}
#Override
public void onFailure(int statusCode, Header[] headers, String res, Throwable t) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
Toast.makeText(getApplicationContext(),"Bad Request",Toast.LENGTH_LONG);
}
}
);
Here are the snippet of node.js and mongodb server running:
node.js
Host unreachable error
Trying to upload a file with params using loopj.
im trying to get file from Request.Files and params from Request.Form["create"]
but it is not uploading to the server.
Android Post method
try {
String createTeamURL = "http://url";
RequestParams params = new RequestParams();
params.put("file", new File(pathoffile));
params.add("create", regString);
AsyncHttpClient client = new AsyncHttpClient();
client.post(createTeamURL, params, new AsyncHttpResponseHandler() {
#Override
public void onStart() {
// called before request is started
}
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// called when response HTTP status is "200 OK"
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
}
#Override
public void onRetry(int retryNo) {
// called when request is retried
}
});
} catch (Exception e) {
Log.e("createTeamPreStep", e.getMessage());
}
My Web Api c# method
[HttpPost]
public async Task<string> CreateUHS()
{
var resultString = "";
foreach(HttpPostedFileBase s in Request.Files)
{
var a=s;
}
String sdf = Request.Form["create"];
}
You need to use put for string args.
please find the below both server and client methods.
and one more thing im really worried about your naming variable. its bad. please change it. Happy coding.
String createTeamURL = "http://url";
RequestParams params = new RequestParams();
params.put("file", new File(pathoffile));
params.put("create", regString);
Server (Web api)
[HttpPost]
public async Task<string> CreateUHS()
{
var file=Request.Files[0];
String otherArg = Request.Form["create"];
}
I used LoopJ AndroidAsyncHttp to get the response from the url, but the code didn't go into onSuccess() or onFailure(). The code is as below:
public void queryTopic(RequestParams params) {
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://192.168.0.109:8080/PhoneServer/topic/query", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
System.out.println("It's in onSuccess");
}
// When the response returned by REST has Http response code
// other than '200'
#Override
public void onFailure(int statusCode, Throwable error,
String content) {
System.out.println("It's in onFailure");
}
});
System.out.println("It's over");
}
It just printed out the "It's over". What's the matter with the AsyncHttpClient?
How are you calling this? Is the context alive? If you are calling it from some place where context is no more available, then you will never get this callbacks.
I think you should try calling this queryTopic() method on click of some button and then wait for some time, you should get the response.
maybe the problem is that you ask to the server for a String
public void onSuccess(String response){...}
but server answer with a JSONObject
You can try this code:
AsyncHttpClient client = new AsyncHttpClient();
client.setTimeout(5000);
client.get(yourActivity.class, yourLink, new JsonHttpResponseHandler(){
#Override
public void onStart() {
Log.e(TAG, "start");
}
#Override
public void onSuccess(int status, Header[] headers, JSONObject answer) {
Log.e(TAG, "SUCCESS");
Log.e(TAG, "print => "+answer.getString("answer_id")); //"answer_id" is a random example
}
#Override
public void onFailure(int status, Header[] headers, String answer, Throwable throwable) {
Log.e(TAG, "FAILURE");
}
});
onSuccess() is an overloaded method be careful regarding what you send from server,
if it is a jsonObject or jsonArray or simple string. Use corresponding overloaded method of onSuccess(). I am using it too for a jsonObject response and i confront no error or irregularities in the method.
I return jsonObject from server for which my code works as expected and is as follows:
RequestParams params = new RequestParams();
params.put("pet","Cat");
params.put("name","Maran");
RestClient.get("/savelocation", params, new JsonHttpResponseHandler(){
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
Toast.makeText(context,response.toString(),Toast.LENGTH_SHORT).show();
Log.e("Error makerequest","request completed");
}
#Override
public void onFinish() {
//onLoginSuccess();
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable,JSONObject errorResponse){
Toast.makeText(context,throwable.toString(),Toast.LENGTH_LONG).show();
}
});
Note: RestClient is a static instance of AsyncHttpClient
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
I'm using Loopj's AsyncHttpClient to do http requests with JSON data. Now I need to get the http error code that is returned from the server. Where can I find that?
The handler that I pass looks like this:
new JsonHttpResponseHandler()
{
#Override
public void onFailure(Throwable throwable, JSONObject object)
{
// Get error code
}
}
Is this not possible at all?
Try this:
HttpResponseException hre = (HttpResponseException) throwable;
int statusCode = hre.getStatusCode();
It should work only for status code >= 300, because of following code in AysncHttpResponseHandler class in loopj
if(status.getStatusCode() >= 300) {
sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()), responseBody);
}
Give a look at client.post(null, url, entity, "application/json", responseHandler);
Declare method as given in below and you will you will get status code
RestClientAvaal.post(url, entity, new BaseJsonHttpResponseHandler<>() {
#Override
public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, Object response) {
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, Object errorResponse) {
}
#Override
protected Object parseResponse(String rawJsonData, boolean isFailure) throws Throwable {
return null;
}
});
And if you want to get exception message then try new Exception(throwable).getMessage() in onFailure method