简体   繁体   English

Android将Java中的POST请求发送到ASP.net Web API

[英]Android send POST request in Java to ASP.net Web API

When I used HttpUrlConnection to send POST request from Android to ASP.net Web API. 当我使用HttpUrlConnection将POST请求从Android发送到ASP.net Web API时。 It seems not working. 看来不行。

String baseUrl = "http://<IP Address>/Save/Document";
URL url = new URL(baseUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
DataOutputStream os = new DataOutputStream(conn.getOutputStream());

JSONObject ap = new JSONObject();
// Where data is a JSON string
// Like [{Test: 1}, {Test: 2}]
ap.put("",new Gson().toJson(data));

OutputStreamWriter ap_osw= new OutputStreamWriter(conn.getOutputStream());
ap_osw.write(ap.toString());
ap_osw.flush();
ap_osw.close();

BufferedReader br = new BufferedReader(new InputStreamReader(
                    (conn.getInputStream())));

StringBuilder response = new StringBuilder();
while ((output = br.readLine()) != null) {
    response.append(output);
    response.append('\r');
}
String mes = response.toString();
Log.i("INFO", mes);
conn.disconnect();

When executing the above code, it will have an FileNotFoundException in 执行上面的代码时,它将在其中具有FileNotFoundException

conn.getInputStream()

I also tried to implement source code in HttpClient style. 我还尝试以HttpClient样式实现源代码。

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(baseUrl);

try {
     StringEntity se = new StringEntity((new Gson()).toJson(data));
     httpPost.setEntity(se);
     httpPost.setHeader("Accept", "application/json");
     httpPost.setHeader("Content-Type", "application/json");

     HttpResponse response = httpClient.execute(httpPost);
     InputStream inputStream = response.getEntity().getContent();

     String result = "";
     if (inputStream != null)
          result = convertInputStreamToString(inputStream);
     else
          result = "Did not work!";

     Log.i("RESPONSE", result);

 } catch (Exception ex) {
     Log.i("Exception", ex.getMessage());
 }
 return output;

And this time, it shows "The requested resource does not support http method 'get'". 并且这一次,它显示“请求的资源不支持http方法'get'”。

I have no ideas how to implement the POST request method to send data from Android to ASP.net Web API. 我不知道如何实现POST请求方法以将数据从Android发送到ASP.net Web API。 Any recommendations? 有什么建议吗?

Finally, the following coding is my ASP.net Web API for reference. 最后,以下编码是我的ASP.net Web API供参考。

[HttpPost]
[Route("Save/Document")]
public HttpResponseMessage Post([FromBody]string model)
{
     var resp = new HttpResponseMessage(HttpStatusCode.OK);
     resp.Content = new StringContent(model, System.Text.Encoding.UTF8, "text/plain");
     return resp;
}

Finally, I got a solution to fix this problem. 最后,我找到了解决此问题的解决方案。 It is due to the POST data in request body can not be read from Web API. 这是由于无法从Web API读取请求正文中的POST数据。

When the request Content-Type is "application/json", 当请求的Content-Type为“ application / json”时,

Using string, The request body should be a plain text (eg "Text Message"). 使用字符串,请求正文应为纯文本(例如,“文本消息”)。

[FromBody] string inStr

Using self-defined class, The request body should be a json string (eg { KEY: VALUE }) 使用自定义类,请求主体应为json字符串(例如{KEY:VALUE})

[FromBody] YourClass inObj

Using array of self-defined class, The request body should be a json array string (eg [{ KEY: VALUE }]) 使用自定义类的数组,请求主体应为json数组字符串(例如[{KEY:VALUE}])

[FromBody] YourClass[] inObj

And the self-defined class should be like as following:- 并且自定义类应如下所示:

class YourClass {
    public string KEY { get; set; }
}

Btw. 顺便说一句。 Thanks for all reply and useful information. 感谢您的所有答复和有用的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM