how to send post request in android - android

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

Related

send data in raw using asynhttpclient

I m posting JSON in raw with this Url [URL I post data to][1]
param is=eventName="countryList"
codes
private void testApp() {
try {
JSONObject jsonParams = new JSONObject();
jsonParams.put("key", "value");
StringEntity entity = new StringEntity(new Gson().toJson(jsonParams));
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
AsyncHttpClient client = new AsyncHttpClient();
client.post(getApplicationContext(), "url", entity, "application/json", new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
super.onSuccess(statusCode, headers, response);
Log.e("good",response.toString());
}
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Log.e("fail",throwable.toString());
}
});
} catch (Exception e) {
}
}
error:fail: cz.msebera.android.httpclient.client.HttpResponseException: Internal Server Error
change fromStringEntity entity = new StringEntity(new Gson().toJson(jsonParams));
to:**StringEntity stringEntity = new StringEntity(jsonParams.toString());**
And Also override
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
}
your response return jsonobject not array

Upload image with loopj android to slim framework based REST api?

I am trying to upload image using Params.
Android code:
POST Data to Server
RequestParams params = new RequestParams();
params.put("item_name", "Name of item");
params.put("item_image", encodedImage);
MyRestClient.post(MainActivity.this, "item",params, new JsonHttpResponseHandler(){
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
JSONArray jArr = response;
super.onSuccess(statusCode, headers, response);
}
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
String responseFromAPI = responseString;
super.onFailure(statusCode, headers, responseString, throwable);
}
#Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
String responseStr = responseString;
super.onSuccess(statusCode, headers, responseString);
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
JSONObject jObj = response;
super.onSuccess(statusCode, headers, response);
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
JSONObject jOBj = errorResponse;
super.onFailure(statusCode, headers, throwable, errorResponse);
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
JSONArray jArr = errorResponse;
super.onFailure(statusCode, headers, throwable, errorResponse);
}
});
Bitmap Image Encode
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
Slim Framework Code:
$app->post('/image', function ($request, $response) {
$input = $request->getParsedBody();
$uploaded_image = $input['image_image'];
$path = "/..../uploads/"."img-".date("Y-m-d-H-m-s").".jpg";
if (file_put_contents($path, base64_decode($uploaded_image)) != false)
{
$sql = "INSERT INTO item (item_name, item_image) VALUES (:restaurant_name, :restaurant_image)";
$sth = $this->db->prepare($sql);
$sth->bindParam("item_name", $input['item_name']);
$sth->bindParam("item_image", $input['item_image']);
$sth->execute();
$input['id'] = $this->db->lastInsertId();
}
return $this->response->withJson($input);
});
Problem:
The photo should be uploaded as per the code and my understanding. It is not uploading the image to the desired folder.
Am I doing things correctly or have I missed something?
<?php
$app->post('/image', function ($request, $response) {
$files = $request->getUploadedFiles();
$file = $files['image_image']; // uploaded file
$parameters = $request->getParams(); // Other POST params
$path = "/..../uploads/"."img-".date("Y-m-d-H-m-s").".jpg";
if ($file->getError() === UPLOAD_ERR_OK) {
$file->moveTo($path); // Save file
// DB interactions here...
$sql = "INSERT INTO item (item_name, item_image) VALUES (:restaurant_name, :restaurant_image)";
$sth = $this->db->prepare($sql);
$sth->bindParam("item_name", $input['item_name']);
$sth->bindParam("item_image", $input['item_image']);
// if statement is executed successfully, return id of the last inserted restaraunt
if ($sth->execute()) {
return $response->withJson($this->db->lastInsertId());
} else {
// else throw exception - Slim will return 500 error
throw new \Exception('Failed to persist restaraunt');
}
} else {
throw new \Exception('File upload error');
}
});

How to get existing payment method from braintree in android?

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?

onFailure not getting called - onFailure(...) was not overriden, but callback was receiced

I am using android-async-http library from Loopj, onFailure not getting called in my code, I have tried all three methods..
W/JsonHttpRH﹕ onFailure(int, Header[], String, Throwable) was not overriden, but callback was received
private void get() {
//Request parameters
RequestParams params = new RequestParams();
params.put("key", API_KEY);
MyRESTClient.get("/posts/", null, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
//some code
}
#Override
public void onProgress(long bytesWritten, long totalSize) {
mLoaderProgress.setText((long) 100 * bytesWritten / totalSize + "Loading...");
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
Log.d("Error----> ", ""+statusCode+" ------ "+ errorResponse);
}
});
}
Below is correct method to override,
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Log.d("Failed: ", ""+statusCode);
Log.d("Error : ", "" + throwable);
}
You need to override correct method . Some of the onFailure are :
1.public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse)
2.public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse)
3.public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable)
Choose the proper onFailure to avoid the error.
Use this for Header
import cz.msebera.android.httpclient.Header;

android - GET-request with Loopj

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

Categories

Resources