我在 ASP.net 端实现了一个 Web API 服务,并想从 Android 调用它,但发送的消息为空“类型已成功上传:!”
。发送的数据应打印在冒号和感叹号之间。
我还检查了数据库,添加了一个带有空值的类型。我还检查了 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 Web 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 注入(inject)。
关于android - 在 Android 中调用 .NET Web API Post Service 发送空消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53598672/