我已经在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();
}
答案 0 :(得分:3)
两件事,
在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注入。