Android http post with composed objects - android

I'm trying to invoke a REST web service from Android with . For this purpose i created a class like this:
public class HttpUtils {
public static final String BASE_URL1 = AppConstants.hostname;
private static AsyncHttpClient client = new AsyncHttpClient(true, 80, 443);
public HttpUtils() throws NoSuchAlgorithmException {
}
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 relativeUrl;
}
Then i created a service layer in order to call the method post. The customer gave me the structure of JSON to send:
{
"wsMode":"nuovo",
"wsTokenLogin":"&1I1BY!M$$YEMFKI0YX&",
"crmcttCognome": "Xavi",
"crmcttNome": "Alonso",
"crmcttIndirizzo": "via Alcide de Gasperi",
"crmcttCivico": "1",
"crmcttLocalita": "Napoli",
"crmcttCdLocalita": "",
"crmcttProv": "NA",
"crmcttCap": "80100",
"crmcttTel1": "08123232332",
"crmcttTel2": "",
"crmcttMobile1": "",
"crmcttMobile2": "",
"crmcttEmail1": "",
"crmcttEmail2": "",
"crmcttNota": "ok",
"crmcttIdstcontatto": "N",
"crmcttIdpromoter": "61",
"crmcttDtRilevaz": "20180806",
"crmcttOraRilevaz": "1530",
"crmcttLuogoRilevaz": "",
"prodotti": [{
"crmcprIdprodotto": "01",
"crmprdCdprodotto": "MATE",
"crmprdDsprodotto": "MATERASSI"
}]}
The request i have created has the following structure:
RequestParams rp = new RequestParams();
rp.put("wsMode", "nuovo");
rp.put("wsTokenLogin", token);
rp.put("crmcttCognome", lead.getCognome());
rp.put("crmcttNome", lead.getNome());
rp.put("crmcttIndirizzo", lead.getIndirizzo());
rp.put("crmcttCivico", lead.getCivico());
rp.put("crmcttLocalita", lead.getLocalita());
rp.put("crmcttCdLocalita", lead.getCdLocalita());
rp.put("crmcttProv", lead.getProvincia());
rp.put("crmcttCap", lead.getCap());
rp.put("crmcttTel1", lead.getTelefono1());
rp.put("crmcttTel2", lead.getTelefono2());
rp.put("crmcttMobile1", lead.getMobile1());
rp.put("crmcttMobile2", lead.getMobile2());
rp.put("crmcttEmail1", lead.getEmail1());
rp.put("crmcttEmail2", lead.getEmail2());
rp.put("crmcttNota", lead.getNota());
rp.put("crmcttIdstcontatto", lead.getIdContatto());
rp.put("crmcttIdpromoter", lead.getIdPromoter());
rp.put("crmcttDtRilevaz", lead.getDataRilevazione());
rp.put("crmcttOraRilevaz", "");
rp.put("prodotti",prodottiCliente);
rp.setUseJsonStreamer(true);
where prodottiCliente is array of objects that i have transformed into String with:
String jsonProdottiAddClient = gson.toJson(prodottiAddClient);
After the call, all elements are stored into db except "prodotti". In debug i can see that the list is not empty.
If i try to execute the post call by Postman, all information are stored including prodotti informations. Can you give me some advice to solve the problem?

Related

How to call asp.net Web API from android device

I have a web api controller:
// POST: api/CountriesAPI
[ResponseType(typeof(Country))]
public async Task<IHttpActionResult> PostCountry(Country country)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Countries.Add(country);
await db.SaveChangesAsync();
return CreatedAtRoute("DefaultApi", new { id = country.CountryID }, country);
}
I don't know how how to consume this from android. please help.
I've used the Android HTTP Client available here and found it very simple and easy to use.
You can then do a POST with code something like below:
public class HTTPClient
{
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler)
{
client.get(url, params, responseHandler);
}
public static void get(String url, FileAsyncHttpResponseHandler responseHandler)
{
client.get(url, responseHandler);
}
public static void post(Context context, String url, StringEntity entity, String contentType, AsyncHttpResponseHandler responseHandler)
{
client.post(context, url, entity, contentType, responseHandler);
}
}
HTTPClient.post(this, <server_url>, entity, "application/json", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response)
{
// Do Something
}
#Override
public void onFailure(Throwable error, String content)
{
// Do Something else
}
});
You can try Libraries like Volley (Requires you to write boilerplate code) or RetroFit
You can make get and post requests using them, do read about Pojos and model creation before you start. And also how do Callbacks work.

How to pass long as string on url for json response in loopj

Just started learning loopj. how to pass long {id} on url as string?
I have a method in client like this,
public static void getAllByIdForSpinner(Context context, String url, Header[] headers,
RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(context, getAbsoluteUrl(url), headers, params, responseHandler);
}
and in mainactivity
myRestClient.getAllByIdForSpinner(MainActivity.this, "ExampleRestService/product/" +id,
headers.toArray(new Header[headers.size()]), null, new JsonHttpResponseHandler()
I tried few things. But nothing worked for this method.

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.

Static Http Client not giving callbacks

I used Loopj Android library for Post requests it works fine when I don't use Static Http Client but when I use Static Http Client it does not give any callback here is my code for class of HttpClient
import com.loopj.android.http.*;
public class MyHttpClient {
private static final String BASE_URL = "http://www.google.com";
private static AsyncHttpClient client = new AsyncHttpClient();
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
System.out.println("post called");
}
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(getAbsoluteUrl(url), params, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl;
}
}
Here is how I call it
MyHttpClient.post("", params, new AsyncHttpResponseHandler(){
#Override
public void onSuccess(String response) {
System.out.println(response);
}
});
and I have added Internet permission in manifest so there is no issue of permissions here
kindly help

POSTing JSON/XML using android-async-http (loopj)

I am using android-async-http and really liking it. I've run into a problem with POSTing data. I have to post data to the API in the following format: -
<request>
<notes>Test api support</notes>
<hours>3</hours>
<project_id type="integer">3</project_id>
<task_id type="integer">14</task_id>
<spent_at type="date">Tue, 17 Oct 2006</spent_at>
</request>
As per the documentation, I tried doing it using RequestParams, but it is failing. Is this any other way to do it? I can POST equivalent JSON too. Any ideas?
Loopj POST examples - extended from their Twitter example:
private static AsyncHttpClient client = new AsyncHttpClient();
To post normally via RequestParams:
RequestParams params = new RequestParams();
params.put("notes", "Test api support");
client.post(restApiUrl, params, responseHandler);
To post JSON:
JSONObject jsonParams = new JSONObject();
jsonParams.put("notes", "Test api support");
StringEntity entity = new StringEntity(jsonParams.toString());
client.post(context, restApiUrl, entity, "application/json",
responseHandler);
#Timothy answer did not work for me.
I defined the Content-Type of the StringEntity to make it work:
JSONObject jsonParams = new JSONObject();
jsonParams.put("notes", "Test api support");
StringEntity entity = new StringEntity(jsonParams.toString());
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
client.post(context, restApiUrl, entity, "application/json", responseHandler);
Good Luck :)
a better way to post json
RequestParams params = new RequestParams();
params.put("id", propertyID);
params.put("lt", newPoint.latitude);
params.put("lg", newPoint.longitude);
params.setUseJsonStreamer(true);
ScaanRestClient restClient = new ScaanRestClient(getApplicationContext());
restClient.post("/api-builtin/properties/v1.0/edit/location/", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
}
});
To post XML
protected void makePost() {
AsyncHttpClient client = new AsyncHttpClient();
Context context = this.getApplicationContext();
String url = URL_String;
String xml = XML-String;
HttpEntity entity;
try {
entity = new StringEntity(xml, "UTF-8");
} catch (IllegalArgumentException e) {
Log.d("HTTP", "StringEntity: IllegalArgumentException");
return;
} catch (UnsupportedEncodingException e) {
Log.d("HTTP", "StringEntity: UnsupportedEncodingException");
return;
}
String contentType = "string/xml;UTF-8";
Log.d("HTTP", "Post...");
client.post( context, url, entity, contentType, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
Log.d("HTTP", "onSuccess: " + response);
}
... other handlers
});
}
just write your xml or json to a string and send to server, with proper headers or without. and yes set "Content-Type" to "application/json"
If someone have a problem that httpclient send as Content-Type: text/plain, please refer this link: https://stackoverflow.com/a/26425401/361100
The loopj httpclient is somewhat changed (or has problem) which cannot override StringEntity native Content-Type to application/json.
You can add the JSON string as an InputStream of some kind - I've used the ByteArrayStream, then passing it to the RequestParams you should set the correctMimeType
InputStream stream = new ByteArrayInputStream(jsonParams.toString().getBytes(Charset.forName("UTF-8")));
multiPartEntity.put("model", stream, "parameters", Constants.MIME_TYPE_JSON);
Just make JSONObject and then convert it to String "someData" and simply send with "ByteArrayEntity"
private static AsyncHttpClient client = new AsyncHttpClient();
String someData;
ByteArrayEntity be = new ByteArrayEntity(someData.toString().getBytes());
client.post(context, url, be, "application/json", responseHandler);
It is working fine for me.
To post xml file to a php server :
public class MainActivity extends AppCompatActivity {
/**
* Send xml file to server via asynchttpclient lib
*/
Button button;
String url = "http://xxx/index.php";
String filePath = Environment.getExternalStorageDirectory()+"/Download/testUpload.xml";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
postFile();
}
});
}
public void postFile(){
Log.i("xml","Sending... ");
RequestParams params = new RequestParams();
try {
params.put("key",new File(filePath));
}catch (FileNotFoundException e){
e.printStackTrace();
}
AsyncHttpClient client = new AsyncHttpClient();
client.post(url, params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int i, cz.msebera.android.httpclient.Header[] headers, byte[] bytes) {
Log.i("xml","StatusCode : "+i);
}
#Override
public void onFailure(int i, cz.msebera.android.httpclient.Header[] headers, byte[] bytes, Throwable throwable) {
Log.i("xml","Sending failed");
}
#Override
public void onProgress(long bytesWritten, long totalSize) {
Log.i("xml","Progress : "+bytesWritten);
}
});
}
}
After adding android-async-http-1.4.9.jar to android studio,
go to build.gradle and add :
compile 'com.loopj.android:android-async-http:1.4.9' under dependencies
And on AndroidManifest.xml add:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Categories

Resources