在 Android 中调用 .NET Web API Post 服务发送空消息
Calling .NET Web API Post Service in Android sends null message
我在 ASP.net 端实现了 Web API 服务,想从 Android 调用它,但发送的消息为空 "type has been uploaded successfully: !"
。发送的数据应该打印在冒号和感叹号之间。
我还检查了数据库,添加了一个具有空值的类型。我还检查了 Fiddler 上的 Web API,它在我发送字符串值时工作正常。那么我怎样才能正确发送数据呢?提前致谢。
ASP.net边
[HttpPost]
public String SetType([FromBody]string type)
{
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MConnectionString"].ConnectionString);
try
{
connection.Open();
SqlCommand cmd = new SqlCommand("insert into [MeasureType] (type_name) values (' " + type + " ')", connection);
cmd.ExecuteNonQuery();
return "type has been uploaded successfully : " + type + " !";
}
catch (Exception exception)
{
return exception.Message + "error uploading type";
}
finally
{
connection.Close();
}
}
Android 侧
public String SetMeasureType(String type)
{
java.net.URL url = null;
StringBuilder builder = new StringBuilder();
HttpURLConnection connection = null;
try {
url = new URL("http://192.168.1.140:65079/api/monitoringtool/SetType");
// open a connection
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true); // to get request only
connection.setDoOutput(true); // upload a request body
connection.setUseCaches(false);
connection.setRequestMethod("POST"); // request method post
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Content-Length","" + Integer.toString(type.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setConnectTimeout(3000); // connection time out
connection.setReadTimeout(3000); // read time out
// Send request
OutputStream outStream = new BufferedOutputStream(connection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outStream, "UTF-8"));
writer.write(type);
writer.flush();
writer.close();
outStream.close();
// get response
InputStream inStream = connection.getInputStream(); // input stream of connection to get data
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream)); // reader for reading data from stream
String line;
while((line = reader.readLine()) != null)
{
builder.append(line);
}
int responseCode = connection.getResponseCode();
reader.close();
if(responseCode == HttpURLConnection.HTTP_OK)
{
return builder.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (connection != null) {
connection.disconnect();
}
}
return builder.toString();
}
两件事,
在 Android 端发送一个实际的 JSON 字符串
//...
//construct JSON
String json = "{\"type\":\"" + type + "\"}";
connection.setRequestProperty("Content-Length","" + Integer.toString(json.getBytes().length));
//send
writer.write(json);
//...
在 ASP.net 网络 API 端,
创建一个模型来表示要接收的数据
public class TypeModel {
public string type { get; set; }
}
并更新 ApiController
动作以期望模型
[HttpPost]
public IHttpActionResult SetType([FromBody]TypeModel model) {
if (!ModelState.IsValid) return BadRequest(ModelState);
var connectionString = ConfigurationManager.ConnectionStrings["MConnectionString"].ConnectionString;
using (var connection = new SqlConnection(connectionString)) {
try {
var type = model.type;
connection.Open();
var cmd = new SqlCommand("insert into [MeasureType] (type_name) values (@type)", connection);
var parameter = cmd.CreateParameter();
parameter.ParameterName = "@type";
parameter.Value = type;
cmd.Parameters.Add(parameter);
return Ok("type has been uploaded successfully : " + type + " !");
} catch (Exception exception) {
return InternalServerError(exception);
}
}
}
还要注意参数的使用,避免SQL注入。
我在 ASP.net 端实现了 Web API 服务,想从 Android 调用它,但发送的消息为空 "type has been uploaded successfully: !"
。发送的数据应该打印在冒号和感叹号之间。
我还检查了数据库,添加了一个具有空值的类型。我还检查了 Fiddler 上的 Web API,它在我发送字符串值时工作正常。那么我怎样才能正确发送数据呢?提前致谢。
ASP.net边
[HttpPost]
public String SetType([FromBody]string type)
{
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MConnectionString"].ConnectionString);
try
{
connection.Open();
SqlCommand cmd = new SqlCommand("insert into [MeasureType] (type_name) values (' " + type + " ')", connection);
cmd.ExecuteNonQuery();
return "type has been uploaded successfully : " + type + " !";
}
catch (Exception exception)
{
return exception.Message + "error uploading type";
}
finally
{
connection.Close();
}
}
Android 侧
public String SetMeasureType(String type)
{
java.net.URL url = null;
StringBuilder builder = new StringBuilder();
HttpURLConnection connection = null;
try {
url = new URL("http://192.168.1.140:65079/api/monitoringtool/SetType");
// open a connection
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true); // to get request only
connection.setDoOutput(true); // upload a request body
connection.setUseCaches(false);
connection.setRequestMethod("POST"); // request method post
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Content-Length","" + Integer.toString(type.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setConnectTimeout(3000); // connection time out
connection.setReadTimeout(3000); // read time out
// Send request
OutputStream outStream = new BufferedOutputStream(connection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outStream, "UTF-8"));
writer.write(type);
writer.flush();
writer.close();
outStream.close();
// get response
InputStream inStream = connection.getInputStream(); // input stream of connection to get data
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream)); // reader for reading data from stream
String line;
while((line = reader.readLine()) != null)
{
builder.append(line);
}
int responseCode = connection.getResponseCode();
reader.close();
if(responseCode == HttpURLConnection.HTTP_OK)
{
return builder.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (connection != null) {
connection.disconnect();
}
}
return builder.toString();
}
两件事,
在 Android 端发送一个实际的 JSON 字符串
//...
//construct JSON
String json = "{\"type\":\"" + type + "\"}";
connection.setRequestProperty("Content-Length","" + Integer.toString(json.getBytes().length));
//send
writer.write(json);
//...
在 ASP.net 网络 API 端,
创建一个模型来表示要接收的数据
public class TypeModel {
public string type { get; set; }
}
并更新 ApiController
动作以期望模型
[HttpPost]
public IHttpActionResult SetType([FromBody]TypeModel model) {
if (!ModelState.IsValid) return BadRequest(ModelState);
var connectionString = ConfigurationManager.ConnectionStrings["MConnectionString"].ConnectionString;
using (var connection = new SqlConnection(connectionString)) {
try {
var type = model.type;
connection.Open();
var cmd = new SqlCommand("insert into [MeasureType] (type_name) values (@type)", connection);
var parameter = cmd.CreateParameter();
parameter.ParameterName = "@type";
parameter.Value = type;
cmd.Parameters.Add(parameter);
return Ok("type has been uploaded successfully : " + type + " !");
} catch (Exception exception) {
return InternalServerError(exception);
}
}
}
还要注意参数的使用,避免SQL注入。