LoopJ AndroidAsyncHttp Server Response after POST Android - 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) {}
);

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

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

Paypal Future Payments: What HTTP requests do I send on the mobile device (Android)?

The Paypal Future Payments demo is pretty thorough, but I'm still a bit confused on what to send from the mobile application.
private void sendAuthorizationToServer(final PayPalAuthorization authorization) {
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("auth", authorization.toJSONObject());
client.post("https://api.sandbox.paypal.com/v1/payments/payment", params,
new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.i("success:", String.valueOf(responseBody));
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.i("err:", String.valueOf(error));
}
}
);
What URL do i put
public void onFuturePaymentPurchasePressed(View pressed) {
// Get the Client Metadata ID from the SDK
String metadataId = PayPalConfiguration.getClientMetadataId(this);
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("metaId", metadataId);
client.post("https://api.sandbox.paypal.com/v1/payments/payment", params,
new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.i("success:", String.valueOf(responseBody));
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.i("err:", String.valueOf(error));
}
}
);
}
I apologize if you feel this to be evident in the documentation. I have just been struggling for the past couple of days trying to find out what to put as the HTTP request.
The implementation of sendAuthorizationToServer() should post the authorization response to your servers, NOT to PayPal servers. Once the authorization response is received from your app, your server should do the token exchanges described here. The resulting token(s) may then be used to create payments (for which your user has consented to) from your server.
At some point in the future when a purchase is initiated within your mobile app, your app should get Client Metadata ID and send it to your server for inclusion when creating the payment request, as described here.
Hope this helps.

LoopJ Android Asynchronous Http Client onpostexecute?

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

Categories

Resources