[英]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). 我尝试将json数据从android app(java) 发送到服务器Web API(ASP .NET )。 But when I post data from android in server side I cant see any data.
但是,当我在服务器端从android发布数据时,我看不到任何数据。 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 android中的客户端cide在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 .
非常感谢@jpgrassi。 It was in server side .
它在服务器端。 I was sending a JSON object but are expecting a string in my POST action.
我正在发送JSON对象,但是在我的POST操作中需要一个字符串。 Simple way to fix this is creating a class that maps to my JSON object:
解决此问题的简单方法是创建一个映射到我的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;}
}
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.
.. ..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.