簡體   English   中英

如何獲取字符串的URL連接結果?

[英]How to get the URL connection result in a string?

我正在使用Yahoo boss API。 該URL應該返回JSON,我需要將其存儲在字符串中然后進行解析。 http://developer.yahoo.com/java/howto-parseRestJava.html

我的問題:如何將URL響應保存在字符串中?

從技術上講,您想在URL InputStream周圍包裝適當配置的InputStreamReader並將Reader復制到StringWriter(apache commons IO具有“ 將Reader復制到String ”實用程序方法)。 但是,為了確定InputStreamReader的正確字符集,您需要解析ContentType標頭。 在這種情況下,最好使用諸如apache commons HttpClient之類的更高級別的庫。

或者,您可以將JSONTokener包裹在URL InputStream周圍,並直接從JSONTokener解析JSONObject(盡管我不能完全確定令牌生成器如何確定正確的字符集,因此使用HttpClient之類的方法可能會更安全)。

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();
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM