HttpUrlConnection을 사용하여 Android에서 ASP.net 웹 API로 POST 요청을 보낼 때. 그것은 작동하지 않는 것 같습니다. 위의 코드를 실행할 때안드로이드는 ASP.net 웹 API에 자바로 POST 요청을 보냅니다.
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();
, 그것은 나 또한 HttpClient를 스타일의 소스 코드를 구현하기 위해 노력
conn.getInputStream()
에 FileNotFoundException이있을 것이다.
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'을 지원하지 않습니다.
안드로이드에서 ASP.net 웹 API로 데이터를 보내도록 POST 요청 메소드를 구현하는 방법에 대한 아이디어가 없습니다. 어떤 추천?
마지막으로 다음 코드는 참조 용으로 내 ASP.net 웹 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를 사용하여 요청을 매우 간단하고 효율적으로 할 수 있습니다. –