How to send json data from Android to Asp.net - android

Help me to post json data from Android to Asp.net
Here is my code below. Android sending json data to webapi
public class UploadByTableActivity extends Activity {
final static String url = "https://webapi.com/api/post/";
HttpResponse response;
AsyncHttpClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uploadbytable);
Button btnWO = (Button) findViewById(R.id.btnwo);
btnWorkOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JSONObject jsonParams = new JSONObject();
String username = "id";
String password = "pw";
client = new AsyncHttpClient(true, 80, 443);
client.addHeader(
"Authorization",
"Basic " + Base64.encodeToString(
(username + ":"+ password).getBytes(),Base64.NO_WRAP)
);
client.setEnableRedirects(true);
RequestParams params = new RequestParams();
// params.put("file", new File(pathoffile));
params.put("name", "name1");
params.put("phone", "111-111-1111");
StringEntity entity = null;
try {
entity = new StringEntity(params.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
client.post(null,url,entity, "application/json", new AsyncHttpResponseHandler(Looper.getMainLooper()) {
#Override
public void onSuccess(int i, Header[] headers, byte[] bytes) {
Log.i("appTag", "OK");
}
#Override
public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
Log.i("appTag"," Error = " + throwable.getMessage());
}
});
}
});
}
Try to retrieve jsondata from webapi to asp.net but jsonString is null.
Please help me how to get json data.
[HttpPost]
public string post([FromBody]string jsonString){
return jsonString;
}

Related

How to send post request with x-www-form-urlencoded body with loopj-async-http library

i m trying to post data in body with x-www-form-urlencoded but i failed
private void sendData(final String toekn) {
RequestParams params = new RequestParams();
params.put("_token", toekn);
StringEntity entity=null;
try {
entity = new StringEntity(params.toString());
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
PropClient.post(getBaseContext(), "", entity, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
Log.e("see", response.toString());
Toast.makeText(SplashActivity.this, response.toString()+"", Toast.LENGTH_SHORT).show();
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
// Pull out the first event on the public timeline
// Do something with the response
}
#Override
public void onFailure(int statusCode, Header[] headers, String response, Throwable e) {
}
#Override
public void onRetry(int retryNo) {
// called when request is retried
}
});
}
above is code i have tried but always get failure .. api works perfect in postman i have attached pic for understanding params ..
image1
image2
static class
public class PropClient {
private static final String BASE_URL = "";
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(Context context, String url, StringEntity entity, AsyncHttpResponseHandler responseHandler) {
// client.addHeader("Accept", "application/json");
client.addHeader("Content-Type", "application/x-www-form-urlencoded");
entity.setContentType("application/json");
client.setUserAgent("android");
client.post(context, getAbsoluteUrl(url), entity, "application/json", responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
String url = BASE_URL + relativeUrl;
return url;
}
}
if u want to use volley u can check my answer
compile 'com.android.volley:volley:1.0.0'
private void getVolley(final String token, String url) {
final RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest jsonObjRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(SplashActivity.this, response + " success", Toast.LENGTH_SHORT).show();
Log.e("volley", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(SplashActivity.this, error.toString() + "", Toast.LENGTH_SHORT).show();
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("User-Agent", "android");
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("_token", token);
return params;
}
};
jsonObjRequest.setRetryPolicy(new DefaultRetryPolicy(30 * 1000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonObjRequest);
}
You need to add header like below :-
public static void setHttpClient(AsyncHttpClient c, Application application) {
c.addHeader("Accept-Language", Locale.getDefault().toString());
c.addHeader("Host", HOST);
c.addHeader("Connection", "Keep-Alive");
//noinspection deprecation
c.getHttpClient().getParams()
.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
// Set AppToken
c.addHeader("AppToken", Verifier.getPrivateToken(application));
//c.addHeader("AppToken", "123456");
// setUserAgent
c.setUserAgent(ApiClientHelper.getUserAgent(AppContext.getInstance()));
CLIENT = c;
initSSL(CLIENT);
initSSL(API.mClient);
}
You need to see this link for more info.

How to send JSON data to a server in android?

With all the old methods been deprecated such as http post , response ,http client, string entity etc, i want to know how can i post json data to a server in android in 2017. My app is supposed to register or send JSON data such as email,contact number and password to a server using POST method and in turn server will give JSON response such as status , message and an array named data. Data is an array of only 2 objects (ie token and email). Please Help.
I think you need to try Loopj library for sending Json Data
you can try this link
and also it is quite easy to undestand
You can try another link
try{
AsyncHttpClient client = new AsyncHttpClient();
JSONObject obj = new JSONObject();
obj.put("email",email);
obj.put("contact_number",contact_number);
obj.put("password",password);
entity = new StringEntity(obj.toString());
client.post(getApplicationContext(), "Your_URL", entity, "application/json", new TextHttpResponseHandler() {
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
Log.d("LoginActivity","Failed");
Log.d("LoginActivity","body " + responseString);
}
#Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
Log.d("LoginActivity","data " + responseString);
try {
JSONObject respObj = new JSONObject(responseString);
String data = respObj.toString();
Log.d("LoginActivity","Data : " + data);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}catch (Exception ex){
Log.d("LoginActivity","Getting Exception "+ex.toString());
}
Try like this
private void registerUser(){
final String username = editTextUsername.getText().toString().trim();
final String password = editTextPassword.getText().toString().trim();
final String email = editTextEmail.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this,response,Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_USERNAME,username);
params.put(KEY_PASSWORD,password);
params.put(KEY_EMAIL, email);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}

Android Json Arraylist to Server with Restful Web service

This is my Arraylist which I get from the previous fragment,
listoftags = getArguments().getParcelableArrayList("data");
It works well. Now I have to send this with some parameters like below:
public void volleyJsonObjectRequest(final String SessionID , final String CustomerID, final String ServiceState , final String ServiceID, final String Address, final String PaymentMode, final String CustomerComments , final ArrayList Items){
String REQUEST_TAG = "volleyJsonObjectRequest";
// POST parameters
CustomRequest request = new CustomRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Toast.makeText(SignActivity.this, response.toString(), Toast.LENGTH_SHORT).show();
Log.d("response",""+response.toString());
/* String status = response.optString("StatusMessage");
String actionstatus = response.optString("ActionStatus");
Toast.makeText(getActivity(), ""+status, Toast.LENGTH_SHORT).show();
if(actionstatus.equals("Success"))
{
// Intent i = new Intent(SignActivity.this, LoginActivity.class);
// startActivity(i);
// finish();
}*/
dismissProgress();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Error."+error.toString(), Toast.LENGTH_SHORT).show();
Log.d("response",""+error.toString());
dismissProgress();
}
}) {
/* #Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}*/
public String getBodyContentType()
{
return "application/json; charset=utf-8";
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
JSONArray jsArray = new JSONArray(listoftags);
params.put("SessionID", SessionID);
params.put("CustomerID", CustomerID);
params.put("ServiceState", ServiceState);
params.put("ServiceID", ServiceID);
params.put("Address", Address);
params.put("PaymentMode",PaymentMode);
params.put("CustomerComments",CustomerComments);
params.put("Items",jsArray.toString());
return params;
}
};
AppSingleton.getInstance(getActivity().getApplicationContext())
.addToRequestQueue(request, REQUEST_TAG);
}
but it getting error to me I want to send it like
// server side //
{
"SessionID":"9lm5255sg0ti9",
"CustomerID":"9",
"ServiceState":"Karnataka",
"ServiceID":"3",
"Address":"sfaff",
"PaymentMode":"cash",
"CustomerComments":"this is fine",
"Items":[
{
"ItemId":1,
"Cost":6777,
"Quantity":33333
}
]
}
How can send arraylist, with other strings, as raw data using volley on server.
JsonObjectRequest can be used to execute rest api using json as input.
JsonObject jobj = new JsonObject();
jobj.put("key","value");
jobj.put("key","value");
jobj.put("key","value");
jobj.put("key","value");
JsonObjectRequest request = new JsonObjectRequest(requestURL, jobj, new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
}
});
*Now add this request in request queue of volley.*
Here jobj is containing input parameters. It can contain even json array inside a JsonObject. Let me know in case of any query.
Rather then volley try retrofit. Make pojo model of your object you want to send, you can make that from pojo classes from https://www.jsonschema2pojo.org the send the whole object on restapi
// try the request //
try {
REQUEST QUEUE
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
String URL = url;
JSONObject jsonBody = new JSONObject();
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
Iterator itr = listoftags.iterator();
while(itr.hasNext()){
AddRowItem ad=(AddRowItem)itr.next();
jsonObject.put("ItemId:",1);
jsonObject.put("Cost:",ad.getPrices());
jsonObject.put("Quantity:",ad.getQty());
// Log.d("ItemId:",""+1+" "+"Cost:"+ad.getPrices()+" "+"Quantity:"+ad.getQty());
}
jsonArray.put(jsonObject);
JSON VALUES PUT
jsonBody.put("SessionID", "9kp0851kh6mk3");
jsonBody.put("CustomerID", "9");
jsonBody.put("ServiceState", "Karnataka");
jsonBody.put("ServiceID", "3");
jsonBody.put("Address", "Address Demo");
jsonBody.put("PaymentMode", "cost");
jsonBody.put("CustomerComments", "Android Volley Demo");
jsonBody.put("Items", jsonArray);
final String requestBody = jsonBody.toString();
Log.d("string ---- >",""+requestBody);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
showToast("get value"+response.toString());
try {
JSONObject jObj = new JSONObject(response);
String action = jObj.get("ActionStatus").toString();
String status = jObj.getString("StatusMessage");
{"ActionStatus":"Success","StatusMessage":"Order Created","RefIDName":"OrderID","RefIDValue":19}
showToast("get value"+action);
}
catch (JSONException e)
{
showToast("get error"+e.toString());
Log.d("errorissue",""+e.toString());
}
dismissProgress();
}
}, new Response.ErrorListener() {
// error response //
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
showToast("get error"+error.toString());
dismissProgress();
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
dismissProgress();
}
}
}
// THIS IS THE WAY ISSUE RESLOVED //
THANKS EVERYONE ...

LoopJ AndroidAsyncHttp Library: Server Recieves Null Parameters

I am using the LoopJ AndroidAsyncHttp Library in an Android Project but when I try to get the parameters at the server side, I get null. I tried using PHP & Java same result. I am 100% sure my server side is working since I use postman chrome plugin and it works:
Client Code:
public void sendRequest(View v) {
try {
AsyncHttpClient client = new AsyncHttpClient();
// HashMap<String, String> paramsMap = new HashMap<String,
// String>();
// paramsMap.put("action", "Action Value");
// RequestParams params = new RequestParams(paramsMap);
RequestParams params = new RequestParams();
params.add("action", "insert");
AsyncHttpResponseHandler handler = new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers,
byte[] body) {
System.out.println("On Success --> Status Code: "
+ statusCode);
String response = new String(body);
System.out.println("On Success --> Response: " + response);
}
#Override
public void onFailure(int statusCode, Header[] headers,
byte[] body, Throwable error) {
System.out.println("On Failure --> Status Code: "
+ statusCode);
}
};
String url1 = "http://192.168.1.9:8080/Tester";
String url2 = "http://192.168.1.6/test";
System.out.println("--->>> Params: " + params.toString());
client.post(url1, params, handler);
} catch (Exception e) {
System.out.println("--> Exception: " + e.getMessage());
}
}
Server Code (Java):
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("------->>> " + request.getParameter("action"));
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet FrontEndController</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet FrontEndController at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}

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