I have an android client which makes a call to a flask python server like so:
public void getCustomerPaymentMethods() {
Uri.Builder builder = new Uri.Builder()
.scheme("http")
.authority("www.server.appspot.com")
.appendPath("get_customer_payment_methods")
.appendPath(mCustomerId);
String url = builder.build().toString();
AsyncHttpClient client = new AsyncHttpClient();
client.get(url, new BaseJsonHttpResponseHandler<List<>>() {
#Override
public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, List<> response) {
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, List<> errorResponse) {
// Display UI for no payment methods
mNoPaymentMethodImageView.setVisibility(View.VISIBLE);
mAddPaymentMethodButton.setVisibility(View.VISIBLE);
}
#Override
protected List<> parseResponse(String rawJsonData, boolean isFailure) throws Throwable {
return null;
}
});
}
This is the server side code mapped to the url provided:
#app.route('/get_customer_payment_methods/<cutomerId>')
def get_customer_payment_methods(customerId):
result = braintree.Customer.find(customerId)
return result.payment_methods
What object do I have to save the response from the python server in on the client side?
Related
how to send post request in android
I use async http clint library
I use this methode for get and I need this for post
client.get(getString(R.string.server2) + "culture_types", new TextHttpResponseHandler() {
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
}
#Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
}
}
});
private static AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("param1", "Test"); // Put parameter name
client.post(Url, params, new TextHttpResponseHandler(){
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
}
#Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
}
}
});
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 need to make GET-request to a url consisting JSON-data and try to use Loopj library, but it returnes nothing. I tried to find examples on the Internet but they turned out, maybe, to be obsolete (onSuccess method had different parameters). I tried to adapt my code to that example and what I got:
String AllData=""; AsyncHttpClient client = new AsyncHttpClient();
client.get("wantedUrl", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
for (byte aResponseBody : responseBody) {
AllData += aResponseBody;
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Toast.makeText(getApplicationContext(),"We got an error",Toast.LENGTH_SHORT).show();
}
});
"wantedUrl" is the url with json, but "AllData" remains empty. How to fix it?
You're getting AsyncHttpResponseHandler callback where you're in need of JsonHttpResponseHandler. Use below code to get the things right on track.
String AllData=""; AsyncHttpClient client = new AsyncHttpClient();
client.get("wantedUrl", new JsonHttpResponseHandler(){
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
super.onSuccess(statusCode, headers, response);
//Here response will be received in form of JSONArray
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
//Here response will be received in form of JSONObject
}
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Toast.makeText(getApplicationContext(), "We got an error", Toast.LENGTH_SHORT).show();
}
});
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