简体   繁体   中英

How to send json data to server WEB API from android

I try send json data to server Web API(ASP .NET) from android app(java). But when I post data from android in server side I cant see any data. How do I know that does not work properly client or server side? Any help appreciated, please if you have some information, idea let me know, thank you!

Client cide in android I implement code below POSTActivity.java

public class POSTActivity extends AppCompatActivity implements View.OnClickListener {

TextView tvIsConnected;
Button btnPost;
String TAG = "json";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login_activity_second);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    btnPost.setOnClickListener(this);
}

@Override
public void onClick(View view) {

    switch(view.getId()) {
        case R.id.btnPost:
            if (!validate())
                 new HttpAsyncTask().execute("http://zhaksy-adam.kz/api/Requisitions/PostRequisition");
                 break;
    }

}

    private class HttpAsyncTask extends AsyncTask<String, String, String> {
    @Override
    protected String doInBackground(String... urls) {
        return POST(urls[0]);
    }

public static String POST(String url){
    InputStream inputStream = null;
    String result = "";
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        String json = "";
        JSONObject jsonObject = new JSONObject();


         jsonObject.add("CityID", "1");
         jsonObject.add("TypeID","1");
         jsonObject.add("Title", "SomeTitle");
         jsonObject.add("RegionID", "1");
         jsonObject.add("Phone1", "+7(705)105-78-70");
         jsonObject.add("Decription","<p>Some Description</p>");
         jsonObject.add("Date", "29-02-2016");


         json = jsonObject.toString();
        StringEntity se = new StringEntity(json);
        httpPost.setEntity(se);

        httpPost.setHeader("accept", "json");
        httpPost.setHeader("Content-type", "json");

        HttpResponse httpResponse = httpclient.execute(httpPost);

        inputStream = httpResponse.getEntity().getContent();

        // convert inputstream to string
        if(inputStream != null)
        { result = convertInputStreamToString(inputStream);
             Log.d("json","inputStream result"+result);}
        else
            result = "Did not work!";
            Log.d("json","result"+result);

    } catch (Exception e) {
        Log.d("json","e.getLocalizedMessage()"+ e.getLocalizedMessage());
    }

    //  return result
    return result;
}

    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
        Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
    }
}

private static String convertInputStreamToString(InputStream inputStream) throws IOException {
    BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while((line = bufferedReader.readLine()) != null)
        result += line;

    inputStream.close();
    return result;

}

This is my server side:

[System.Web.Http.HttpPost]
        public HttpResponseMessage PostRequisition([FromBody]string requisition)
        {
            Requisition postReq = new Requisition();
           if (!String.IsNullOrEmpty(requisition))
            {
                dynamic arr = JValue.Parse(requisition);
                //PostReq model = JsonConvert.DeserializeObject<PostReq>(requisition);
                postReq.FullName = arr.FullName;
                postReq.CityID = Convert.ToInt32(arr.CityID);
                postReq.RegionID = Convert.ToInt32(arr.RegionID);
                postReq.TypeID = Convert.ToInt32(arr.TypeID);
                postReq.UserID = 8;
                postReq.Title = arr.Title;
                postReq.Date = Convert.ToDateTime(arr.Date, CultureInfo.CurrentCulture);
                postReq.Decription = arr.Description;
                postReq.Phone1 = arr.Phone1;
                postReq.Activate = false;
                postReq.ClickCount = 0;
                try
                {
                    db.Requisition.Add(postReq);
                    db.SaveChanges();
                    Message msg = new Message();
                    msg.Date = DateTime.Now;
                    msg.Type = "POST";
                    msg.Text = "OK";
                    db.Message.Add(msg);
                    db.SaveChanges();
                    return Request.CreateResponse(HttpStatusCode.OK, postReq);
                }
                catch (Exception ex)
                {
                    Message msg = new Message();
                    msg.Date = DateTime.Now;
                    msg.Type = "POST";
                    msg.Text = "ERROR";
                    db.Message.Add(msg);
                    db.SaveChanges();
                    return Request.CreateResponse(HttpStatusCode.OK, ex.Message);
                }
            }
            else
            {
                Message msg = new Message();
                msg.Date = DateTime.Now;
                msg.Type = "POST";
                msg.Text = "null";
                db.Message.Add(msg);
                db.SaveChanges();
                return Request.CreateResponse(HttpStatusCode.OK, "null");
            }

        }

I found my problem couse. Big thank to @jpgrassi . It was in server side . I was sending a JSON object but are expecting a string in my POST action. Simple way to fix this is creating a class that maps to my JSON object:

public class RequisitionViewModel
{
    public int TypeID {get; set;}
    public string FullName {get; set;}
    public string Title {get; set;}
    public int RegionID {get; set;}
    public int CityID  {get; set;}
    public string Phone1 {get; set;}    
}

Then, change my action signature to:

[FromBody]RequisitionViewModel requisition)

You also don't need all the converting in your code:

postReq.FullName = requisition.FullName;
postReq.CityID = requisition.CityID;
//other fields.

..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM