HttpUrlConnectionを使用してAndroidからASP.net Web APIにPOSTリクエストを送信したとき。それは動作していないようです。上記のコードを実行するとき、それはAndroidからPOSTリクエストをJavaでASP.net Web APIに送信
conn.getInputStream()
内にFileNotFoundExceptionを有するであろう
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();
Iもの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;
今回は「要求されたリソースがhttpメソッド 'get'をサポートしていません」と表示されます。
AndroidからASP.net Web APIにデータを送信するPOSTリクエストメソッドを実装する方法はありません。どんな勧告?
最後に、次のコーディングは参考のために私の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;
}
郵便配達員のように手動でAPIをテストしましたか? –
あなたのアプリで使用する前に –
Retrofit Apiを使用すると、リクエストが非常に簡単で効率的です。 –