The following REST-based Web Service in written in ASP .NET:
public class DeviceInfo {
public string Model { get; set; }
public string Serial { get; set; }
}
public class DeviceManagerController : ApiController {
...
public string Post([FromBody]DeviceInfo info) {
...
}
}
Here is how I am building the JSON object in Android:
URL url = new URL (url);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");
urlConn.connect();
// Send POST output.
JSONObject jsonParam = new JSONObject();
jsonParam.put("Model", "HP");
jsonParam.put("Serial", "1234");
DataOutputStream printout = new DataOutputStream(urlConn.getOutputStream ());
String jsonStr = jsonParam.toString();
String encodedStr = URLEncoder.encode(jsonStr,"UTF-8");
printout.writeChars(encodedStr);
printout.flush ();
printout.close ();
This code successfully invokes the web service. However, the parameter (DeviceInfo) is null.
I even tried passing jsonStr directly instead of encoding them first. However, in this case, although the parameter info
is no longer null, the members Model
and Serial
are still null.
I am wondering if there is something else that I missed. Regards.