c# - 如何在 C# Rest 服务中从 Android 应用程序读取 JSON 数据
问题描述
我对 android 开发和使用 REST 服务以允许在我的服务器上的应用程序和数据库之间进行通信是相当新的。
我一直在开发一个应用程序,它可以提取与我们系统上记录的票证相关的信息。我的 android 应用程序能够成功地使用 REST 服务从我的数据库中获取数据,但是我很难让我的 REST 服务接受来自我的应用程序的 JSON 格式的数据来更新现有票证或创建新票证。
我的 REST 服务是用 C# 编写的
下面是我的 GET 请求的示例,它运行良好,因为有几个参数并且具有 URL 接受的长度:
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "incidentAgent/{agent}/{incID}")] //PASS A 0 incID IF SELECTING ALL
Stream AgentIncidentListing(string agent, string incID);
这是我的 android 应用程序代码,用于生成 JSON 字符串并将 POST 请求发送到我的 Web 服务:
public void updateIncidents(View v){
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
//Declare and initialize text views from the layout
TextView tvidIncidents = (TextView) findViewById(R.id.tvIncidentID);
TextView tvResolution = (TextView)findViewById(R.id.tvResolution );
TextView tvJobCardNo = (TextView)findViewById(R.id.tvJobCardNo );
TextView tvActualHours = (TextView)findViewById(R.id.tvActualHours );
TextView tvBudgetHours = (TextView)findViewById(R.id.tvBudgetHours );
TextView tvTaskDesc = (TextView)findViewById(R.id.tvTaskDesc );
TextView tvOutline = (TextView)findViewById(R.id.tvOutline );
TextView tvProject = (TextView)findViewById(R.id.tvProject );
TextView tvIncidentType = (TextView)findViewById(R.id.tvIncidentType );
TextView tvStatus = (TextView)findViewById(R.id.tvStatus );
TextView tvCustomer = (TextView)findViewById(R.id.tvCustomer );
TextView tvIncidentNumber = (TextView)findViewById(R.id.tvIncidentNumber );
TextView tvDueBy = (TextView)findViewById(R.id.tvDueDate);
URL url = new URL(updateURI);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setRequestProperty("Accept","application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
JSONObject jsonParam = new JSONObject();
jsonParam.put("iIncidentStatusID", tvStatus.getText());
jsonParam.put("iDebtorID", tvCustomer.getText());
jsonParam.put("cOutline", tvOutline.getText());
jsonParam.put("iIncidentTypeID", tvIncidentType.getText());
jsonParam.put("iProjectID", tvProject.getText());
jsonParam.put("ufINCBHours", tvBudgetHours.getText());
jsonParam.put("ufINCAH", tvActualHours.getText());
jsonParam.put("ucINCJN", tvJobCardNo.getText());
jsonParam.put("ucINCTaskDescription", tvTaskDesc.getText());
jsonParam.put("ucINCResolution", tvResolution.getText());
jsonParam.put("dDueBy", tvDueBy.getText());
jsonParam.put("idIncidents", tvidIncidents.getText());
Log.i("JSON", jsonParam.toString());
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
//os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8"));
os.writeBytes(jsonParam.toString());
os.flush();
os.close();
Log.i("STATUS", String.valueOf(conn.getResponseCode()));
Log.i("MSG" , conn.getResponseMessage());
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
我遇到的问题是我完全不知道如何在我的 REST 服务上处理这个 POST 请求。这就是我迄今为止所拥有的:
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "updateIncData")]
void UpdateJsonIncident(RequestData rData);
请求数据类:
public class RequestData
{
[DataMember]
public string details { get; set; }
}
我想要的是能够读取我的 android 应用程序返回的 JSON 字符串,并将相关值分配给我在 UpdateJsonIncident() 函数中的插入或更新语句,以相应地影响我的数据库。
我已经尝试了很多东西,但无法让它发挥作用。在我的办公桌前坐了第二天(目前连续 11 小时)后,我觉得在这里请求帮助是我最后的手段,希望有人能帮助我。
解决方案
所以终于取得了突破。原来我所要做的就是:
1)我创建了一个名为“IncidentData”的类,如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;
namespace xxxxx.Classes
{
[DataContract]
public class IncidentData
{
[DataMember]
public string idIncidents { get; set; }
[DataMember]
public string IncidentStatus { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string cOurRef { get; set; }
[DataMember]
public string cOutline { get; set; }
[DataMember]
public string IncidentType { get; set; }
[DataMember]
public string Project { get; set; }
[DataMember]
public string BudgetedHours { get; set; }
[DataMember]
public string ActualHours { get; set; }
[DataMember]
public string JobCardNumber { get; set; }
[DataMember]
public string TaskDescription { get; set; }
[DataMember]
public string Resolution { get; set; }
[DataMember]
public string dDueBy { get; set; }
}
}
2)像这样改变了我的运营合同:
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "/UpdateJsonIncident")]
bool UpdateJsonIncident(IncidentData incident);
3) 现在,我需要做的就是在 UpdateJsonIncident 函数中访问我的数据,如下所示:
public bool UpdateJsonIncident(IncidentData incident) {
string xxx = incident.cOutline // etc...
}
如果他们面临同样的问题,我希望这有助于为其他人节省大量时间。
推荐阅读
- java - 如何使用 Java 托管我自己的 SMTP 服务器
- oracle - 无法找到或登录 Oracle Cloud DB
- javascript - Highcharts - Adding a suffix to a tooltip in a multi-series chart
- wpf - "ApplicationCommands.Copy not found" error in Visual Studio (XAML Designer)
- r - Show total number of boxes checked NEXT to ActionButton
- authentication - Authenticate to an API with OWASP ZAP without using OpenAPI or Swagger specs
- apache-kafka - Kafka Mirromaker2 producer idempotence and duplicates
- excel - How to generate a copy of a page from a drop down menu in Excel?
- javascript - Jquery : Creating Dynamic Select list
- python - 当在python中达到有界信号量值时,代码停止执行