0

私はYahoo Boss APIに取り組んでいます。URL は JSON を返すはずです。それを文字列に格納して解析する必要があります。http://developer.yahoo.com/java/howto-parseRestJava.html

私の質問: URL 応答を文字列に保存するにはどうすればよいですか??

4

2 に答える 2

0
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);//send a request and receive a response
        System.out.println("HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");

        HttpEntity entity = response.getEntity();

        if (entity != null) {
            // Read the content stream
            InputStream instream = entity.getContent();





            // convert content stream to a String
            String resultString= convertStreamToString(instream);
            instream.close();
            resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"

そしてここに関数がありますconvertStreamToString

private static String convertStreamToString(InputStream is) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
于 2012-07-17T06:50:28.660 に答える
0

技術的には、適切に構成された InputStreamReader を URL InputStream の周りにラップし、Reader を StringWriter にコピーする必要があります (apache commons IO には「copy Reader to String」ユーティリティ メソッドがあります)。ただし、InputStreamReader の正しい文字セットを判別するには、ContentType ヘッダーを解析する必要があります。その場合、apache commons HttpClient のような高レベルのライブラリを使用する方がよい場合があります。

または、JSONTokener を URL InputStream にラップし、JSONObject を JSONTokener から直接解析することもできます (ただし、トークンナーがどのように正しい文字セットを決定するのか完全にはわからないため、HttpClient などを使用する方が安全かもしれません)。

于 2012-07-17T00:22:28.683 に答える