Long polling issue: No response received - android

I have a issue and I need a help. I want to get updates from server via long polling. I'm using this library for server communication. https://github.com/loopj/android-async-http. Here is a code what I'm using
private void connectService() {
AsyncHttpClient httpClient = new AsyncHttpClient();
httpClient.setBasicAuth("key", "");
BaseJsonHttpResponseHandler handler = new BaseJsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, Object response) {
Log.e(TAG, "success body " + rawJsonResponse);
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, Object errorResponse) {
Log.e(TAG, "error " + throwable.toString());
}
#Override
protected Object parseResponse(String rawJsonData, boolean isFailure) throws Throwable {
Log.e(TAG, "response body " + rawJsonData);
return null;
}
#Override
public void onPreProcessResponse(ResponseHandlerInterface instance, HttpResponse response) {
super.onPreProcessResponse(instance, response);
Log.e(TAG, "pre progress " + instance.getRequestURI());
}
};
httpClient.get(this, url, null, handler);
}
So I tested in browser and everything is work, but I didn't get any response on my device and also which library you is the best for using long polling?
Thanks

Related

How to upload all images stored in a file of internal memory

I need to send all images stored in a file. Now am sending one image on button click by specifying its name. But how to send all images on button click saved in some folder
public class UploadImagesToServer {
public static void postImage(String ImageLink){
RequestParams params = new RequestParams();
try {
params.put("file", new File(ImageLink));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
AsyncHttpClient mNewCaller = new AsyncHttpClient();
mNewCaller.get(Constants.MediaUpload, params, new JsonHttpResponseHandler() {
#Override
public void onStart() {
super.onStart();
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
Log.e("response page", response.toString());
}
#Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
super.onSuccess(statusCode, headers, responseString);
Log.e("frag", responseString + " " + statusCode);
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray responseString) {
super.onSuccess(statusCode, headers, responseString);
Log.e("frag", responseString + " " + statusCode);
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
Log.e("fail 3", statusCode + "" + errorResponse);
}
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Log.e("fail 3", statusCode + "" + responseString);
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
Log.e("fail 3", statusCode + "" + errorResponse);
}
});
}
}
the above code is for sending an image
continueBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String filePath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + File.separator + "/Omoto Images/background image.jpg";
UploadImagesToServer.postImage(filePath);
}
});
this is for calling postImage method
Best process for uploading multiple images.
Your image uploading code already implemented you need to just change flow.
You could store your image paths in a list (or something similar) and save the
list (it may be shared preference or sqlite).
As you finish uploading a picture, remove it from that list and continue to the next one, and so on upto your list is empty.
When uploading, if the internet connection drops it will not affect you,
you will always have save the list of images that are still to be uploaded.
For get all images path:
You need to scan directory and store image path and before uploading check path file is exist or not because sometime image may be removed or move.

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.

LoopJ AndroidAsyncHttp didn't go to onSuccess() or onFailure()

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

LoopJ AndroidAsyncHttp PUT, how to do?

I need some help correcting my approach for using the following API > https://github.com/Privo/PRIVO-Hub/wiki/Web-Services-API-Reference#update-user-display-name.
I am unsure of how to send a JSON object for update using LoopJ AndroidAsyncHttp PUT. I am receiving the following error response
{"message":"Error: null","validationErrors":[]."responseTimestamp":141936124612,"totalCount":-1,"status":"failed","resultCount":-1,"entity":null}
How am I doing this wrong?
AsyncHttpClient client = null;
String authorizationHeader = "token_type", "" + " " + "access_token", "");
client.addHeader("Authorization", authorizationHeader);
client.addHeader("Content-type", "application/json");
client.addHeader("Accept", "application/json");
String requestBody = "displayName=" + "hardcodedDisplayName";
String requestURL = "https://privohub.privo.com/api/" + "account/public/saveDisplayName?" + requestBody;
client.put(requestURL, new ResponseHandler(myClass.this, "displayName", new OnResponseHandler() {
#Override
public void onSuccess(int statusCode, String apiName, JSONObject response) {
if (statusCode == 200) {
Log.i(TAG, "Seems to be working")
}
}
#Override
public void onFailure(int statusCode, String apiName, String responseMessage) {
Log.i(TAG, "Fail: " + responseMessage);
}
#Override
public void onFailure(int statusCode, String apiName, JASONArray errorResponse) {
Log.i(TAG, "Fail: " + errorResponse);
}
#Override
public void onFailure(int statusCode, String apiName, JSONObject errorResponse) {
if (errorResponse != null) {
Log.i(TAG, "Fail: " + errorResponse);
}
}
}));
Looks like you are using AsyncHttpClient,
Use the preparePut and AsyncHttpClient.BoundRequestBuilder builder as in the examples/readme,
AsyncHttpClient client = new AsyncHttpClient(); // not null
// other code here
String requestBody = "displayName=" + "hardcodedDisplayName";
String requestURL = "https://privohub.privo.com/api/" + "account/public/saveDisplayName?" + requestBody;
client.preparePut(requestURL) // sets the urls the put request and gets a AsyncHttpClient.BoundRequestBuilder
.setBody(requestBody) // sets the body of the put request
.execute(new AsyncCompletionHandler<Response>(){
#Override
public Response onCompleted(Response response) throws Exception{
// Do something with the Response
// ...
return response;
}
#Override
public void onThrowable(Throwable t){
// Something wrong happened.
}
});

Android: Loopj AsyncHttpClient Get HTTP Error Code

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

Categories

Resources