次のコードでは、春にREST APIにHTTPのPOSTを行います奇妙な挙動は
URLがREST APIエンドポイントが含まれており、データはJSONをして文字列に変換され...
HttpURLConnection connection = null;
InputStream input = null;
BufferedWriter output = null;
BufferedReader reader = null;
String result = null;
try {
connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json");
//Send data
output = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
output.write(data);
output.flush();
//Read response
int responseCode = connection.getResponseCode();
if (responseCode >= 400) {
input = connection.getErrorStream();
} else {
input = connection.getInputStream();
}
reader = new BufferedReader(new InputStreamReader(input));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
result = "Status " + responseCode + ".\n" + sb.toString();
...
POSTで必要なユーザー属性。
問題は、POSTが正常に動作しますが、HTTPステータス201(HTTPステータス409などのエラーが発生した場合でも動作します)を取得した後、APIから返されたレスポンスボディを取得できないということです。不思議なことに、readline()
関数は最初の読み取りで常にnullを返します。 APIはPostman
から完全に呼び出され、Eclipse
のJavaプロジェクトからそのコードを実行しても機能します。
は私のcompileSdkversion
とtargetSdkVersion
私はこことそこに変更を適用し、ネットの周りHttpURLConnection
サンプルの多くの私のコードを比較した25
に設定されますが、ノー成功...
任意のアイデア?
さらに別のサンプルをご覧ください:https://www.tbray.org/ongoing/When/201x/2012/01/17/HttpURLConnection –