9

HttpUrlConnection を使用してサーバーに GET 要求を行います。接続後:

  1. 応答コードを取得します: 200
  2. 応答メッセージが表示されます: OK
  3. 入力ストリームを取得しますが、例外はスローされませんが:

    • スタンドアロン プログラムでは、期待どおり、応答の本文を取得します。

    {"名前":"私の名前","誕生日":"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

アンドロイドで

4

3 に答える 3

13

Tomislav のコードを試してみると答えが出ました。

私の関数 streamToString() は .available() を使用して、受信したデータがあるかどうかを感知し、Android では 0 を返します。確かに、私はそれを呼び出すのが早すぎました。

むしろ readLine() を使用する場合:

class Util {
public static String streamToString(InputStream is) throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    }
}

次に、データが到着するのを待ちます。

ありがとう。

于 2013-02-22T18:54:13.460 に答える
4

文字列で応答を返す次のコードを試すことができます。

public String ReadHttpResponse(String url){
        StringBuilder sb= new StringBuilder();
        HttpClient client= new DefaultHttpClient();     
        HttpGet httpget = new HttpGet(url);     
        try {
            HttpResponse response = client.execute(httpget);
            StatusLine sl = response.getStatusLine();
            int sc = sl.getStatusCode();
            if (sc==200)
            {
                HttpEntity ent = response.getEntity();
                InputStream inpst = ent.getContent();
                BufferedReader rd= new BufferedReader(new InputStreamReader(inpst));
                String line;
                while ((line=rd.readLine())!=null)
                {
                    sb.append(line);
                }
            }
            else
            {
                Log.e("log_tag","I didn't  get the response!");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
于 2013-02-22T17:52:12.543 に答える