LoopJ Android Asynchronous Http Client onpostexecute? - android

I am making a GET call and am able to add all the results into an array after parsing the JSON. I want to use that array onpostexecute call. Can I do that with this library?

I do it in this way , hope it will help you.
in bussiness layer
HttpUtils.getJson(url, null, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
}
});
in HttpUtils.java
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get(String urlString, RequestParams params, AsyncHttpResponseHandler res) //url里面带参数
{
client.get(urlString, params, res);
}

Related

AsyncHttpClient - POST request over HTTPS

I'm developing a new Android app which allow the user to rate the content. The rate is sent thanks to an asynchronous request (POST) over HTTPS. Unfortunately, the request don't reach my webservice. When I took a look at the log access log, the URL is truncated. You can find below the relevant code.
private static AsyncHttpClient getClient()
{
if(client == null)
{
client = new AsyncHttpClient(true, 80, 443);
client.getHttpClient().getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
client.getHttpClient().getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
}
return client;
}
public static void createComment(int idArticle, String content, final Context context, final Callback callback)
{
final User currentUser = RealmManager.getUser();
RequestParams paramsPost = new RequestParams();
paramsPost.put("id_article", idArticle);
paramsPost.put("id_utilisateur", currentUser.getId());
paramsPost.put("content", content);
HashMap<String, String> paramsGet = getDefaultParams(context, currentUser, "webservices.createCommentaire");
getClient().post(createGetURL(currentUser.getURL(), paramsGet), paramsPost, new AsyncHttpResponseHandler()
{
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response)
{
callback.onSuccess(/*..*/);
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e)
{
callback.onFailure(/*..*/);
}
});
}
When I put a breakpoint and examine the request, it looks like :
https://api.webservices.com/index.php?option=webservices&app_version=2.0&task=createCommentaire&token=XXXXXXXXXXXX&version=v2&format=raw
But, in the access log, the URL is truncated after "?" :
POST - https://api.webservices.com/index.php?
Consequently, I got in the response the HTML of the index.php which I can't parse in JSON.
Thank you in advance for your help.
I have two suggestion for you.
Use from UrlEncoder.encode("") method for every part of your parameters
Do not use query string parameters for post data to server.

Loopj - Uploading Files with RequestParams c# .net

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"];
}

How do I call REST API from an android app? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm new to android and new to programming as well. How do I call a REST api (GET/POST request) from an android app. Please suggest me a good tutorial, or give me an idea to start with.
If you want to integrate Retrofit (all steps defined here):
Goto my blog : retrofit with kotlin
Please use android-async-http library.
the link below explains everything step by step.
http://loopj.com/android-async-http/
Here are sample apps:
http://www.techrepublic.com/blog/software-engineer/calling-restful-services-from-your-android-app/
http://blog.strikeiron.com/bid/73189/Integrate-a-REST-API-into-Android-Application-in-less-than-15-minutes
Create a class :
public class HttpUtils {
private static final String BASE_URL = "http://api.twitter.com/1/";
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);
}
public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(url, params, responseHandler);
}
public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(url, params, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl;
}
}
Call Method :
RequestParams rp = new RequestParams();
rp.add("username", "aaa"); rp.add("password", "aaa#123");
HttpUtils.post(AppConstant.URL_FEED, rp, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// If the response is JSONObject instead of expected JSONArray
Log.d("asd", "---------------- this is response : " + response);
try {
JSONObject serverResp = new JSONObject(response.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
// Pull out the first event on the public timeline
}
});
Please grant internet permission in your manifest file.
<uses-permission android:name="android.permission.INTERNET" />
you can add compile 'com.loopj.android:android-async-http:1.4.9' for Header[] and compile 'org.json:json:20160212' for JSONObject in build.gradle file if required.

Multiple Callback Design Pattern?

this question is more design related. Am using the Android Async-Http-Client library http://loopj.com/android-async-http/ to make multiple call request from different methods in a class so my code is something like this
RestClient.post(context, "", entity, "application/json", new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
// Map objects from json using gson
}
});
if different methods in my classes making similar calls like the code Above but with different request params, how can i encapsulate the ResponseHandler Callback so i don't have to keep repeating it in every method call. Was wondering if there is any other nice design pattern method i can use here.
Note
i have thought of subclassing it and as others have suggested, but i can't seem to get the json object response that way.
Thanks
Is the callback behavior identical across all of these requests? If so, you could either create a single shared instance of JsonHttpResponseHandler and use that everywhere:
private JsonHttpResponseHandler handler = new JsonHttpResponseHandler() {
#Override
public void onSuccess(...) {
...
}
}
...
RestClient.post(..., handler);
or you could create a subclass of JsonHttpResponseHandler and use that:
public class MyResponseHandler extends JsonHttpResponseHandler {
#Override
public void onSuccess(...) {
...
}
}
...
RestClient.post(..., new MyResponseHandler());
You dont have to create a new handler for every call.
JsonHttpResponseHandler myHandler = new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
// Map objects from json using gson
}
};
RestClient.post( context, "", entity, "application/json", myHandler );
How about extracting it as a method:
private void restClients(RestClient restClient){
restClient.post(context, "", entity, "application/json", new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
// Map objects from json using gson
}
});
}
Then simply calling the method:
restClients(restclient1)

LoopJ AndroidAsyncHttp Server Response after POST Android

I am using LoopJ AndroidAsyncHttp to get/post data from/to my server. I know that when I call the .get method, the JSON response is stored in the s string as shown below:
client = new AsyncHttpClient();
client.get("https://example.com/generateToken.php", new TextHttpResponseHandler() {
#Override
public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
}
#Override
public void onSuccess(int i, Header[] headers, String s) {}
If, however, I am posting to the server, how do I get my server's response? I used the template here for posting:
http://loopj.com/android-async-http/doc/com/loopj/android/http/RequestParams.html
Specifically my code looks something like this:
params = new RequestParams();
params.put("first_name", firstName);
params.put("last_name", lastName);
client = new AsyncHttpClient();
client.post("xxx.com/createCustomer.php", params, responseHandler);
My server takes these inputs and returns a token. How do I retrieve this token? Do I have to call the .get method as before immediately after the .post code above? Or is it automatically echoed somehow?
Thanks
Its just the same as your Get request.
The Last Paramter in the post Method needs an suitable ResponseHandler.
params = new RequestParams();
params.put("first_name", firstName);
params.put("last_name", lastName);
client = new AsyncHttpClient();
client.post("xxx.com/createCustomer.php", params, new TextHttpResponseHandler() {
#Override
public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
}
#Override
public void onSuccess(int i, Header[] headers, String s) {}
);

Categories

Resources