如何从android发送json数据到服务器WEB API

时间:2016-02-29 10:26:00

标签: java android asp.net json

我从 android 应用程序(java)尝试将json数据发送到服务器Web API(ASP .NET)。但是当我在服务器端从android发布数据时,我看不到任何数据。我怎么知道客户端或服务器端无法正常工作?任何帮助表示感谢,如果您有任何信息,请告诉我,谢谢!

客户端在android中我实现下面的代码 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;

}

这是我的服务器端:

[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");
            }

        }

1 个答案:

答案 0 :(得分:0)

我发现了我的问题。非常感谢@jpgrassi。这是在服务器端。我发送了一个JSON对象,但是在我的POST操作中期待一个字符串。解决这个问题的简单方法是创建一个映射到我的JSON对象的类:

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

然后,将我的操作签名更改为:

[FromBody]RequisitionViewModel requisition)

您也不需要在代码中进行所有转换:

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

...