如何在字符串中获取URL连接结果?

时间:2012-07-17 00:13:13

标签: java json yahoo-api

我正在研究Yahoo boss API。应该返回JSON的URL,我需要将它存储在一个字符串中然后解析它。 http://developer.yahoo.com/java/howto-parseRestJava.html

我的问题:如何在字符串中保存URL响应?

2 个答案:

答案 0 :(得分:0)

从技术上讲,您希望围绕URL InputStream包装适当配置的InputStreamReader,并将Reader复制到StringWriter(apache commons IO具有“copy Reader to String”实用程序方法)。但是,为了确定InputStreamReader的正确字符集,您需要解析ContentType标头。在这种情况下,您可能最好使用更高级别的库,如apache commons HttpClient。

或者,您可以围绕URL InputStream包装JSONTokener并直接从JSONTokener解析JSONObject(虽然我不完全确定tokener如何确定正确的字符集,因此您可能更安全地使用HttpClient之类的东西)。

答案 1 :(得分: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();
    }