HttpUrlConnection を使用してサーバーに GET 要求を行います。接続後:
- 応答コードを取得します: 200
- 応答メッセージが表示されます: OK
入力ストリームを取得しますが、例外はスローされませんが:
- スタンドアロン プログラムでは、期待どおり、応答の本文を取得します。
{"名前":"私の名前","誕生日":"1970/01/01","id":"100002215110084"}
- Android アクティビティでは、ストリームが空 (available() == 0) であるため、テキストを取得できません。
従うべきヒントやトレイルはありますか?ありがとう。
編集:ここにコードがあります
注意してください:私はこれを使用しますimport java.net.HttpURLConnection;
これは標準のhttp Javaライブラリです。他の外部ライブラリを使用したくありません。実際、apache のライブラリ httpclient を使用して Android で問題が発生しました (匿名の .class の一部は、apk コンパイラで使用できません)。
さて、コード:
URLConnection theConnection;
theConnection = new URL("www.example.com?query=value").openConnection();
theConnection.setRequestProperty("Accept-Charset", "UTF-8");
HttpURLConnection httpConn = (HttpURLConnection) theConnection;
int responseCode = httpConn.getResponseCode();
String responseMessage = httpConn.getResponseMessage();
InputStream is = null;
if (responseCode >= 400) {
is = httpConn.getErrorStream();
} else {
is = httpConn.getInputStream();
}
String resp = responseCode + "\n" + responseMessage + "\n>" + Util.streamToString(is) + "<\n";
return resp;
そうですか:
200
OK
レスポンスの本文
だけ
200OK
アンドロイドで