0

我正在尝试使用 httpClient(通过 apache)发布和获取数据。发布绝对没问题,我的代码没有问题,但是,我不能对获取数据说同样的话。

我试图从中获取数据的网站是:http ://www.posttestserver.com/data/2013/04/16/01.13.04594755373

我只想接收帖子的正文(即底部以最近案例开头的 JSON 字符串),但是,我当前使用的方法(以及我在网上找到的每个方法)返回时间、源 IP、标题和正文(基本上它会返回所有内容)。有没有办法解析出这个的主体?我不想遍历返回的字符串并告诉它查找文本“Begin Post Body”,我想要一种自然的方法来执行此操作。那存在吗?

TLDR:我只希望它返回帖子正文中的内容

这是我的代码:

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public static void main(String[] args) throws ClientProtocolException, IOException{

    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet("http://www.posttestserver.com/data/2013/04/16/01.41.38521171013");
    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    System.out.println(EntityUtils.toString(entity));

}

这是返回的内容:

Time: Tue, 16 Apr 13 01:41:38 -0700
Source ip: 155.198.108.247

Headers (Some may be inserted by server)
UNIQUE_ID = UW0OwtBx6hIAACfjfl4AAAAA
CONTENT_LENGTH = 7627
CONTENT_TYPE = application/json
HTTP_HOST = posttestserver.com
HTTP_CONNECTION = close
HTTP_USER_AGENT = Apache-HttpClient/4.2.4 (java 1.5)
REMOTE_ADDR = 155.198.108.247
REMOTE_PORT = 54779
GATEWAY_INTERFACE = CGI/1.1
REQUEST_METHOD = POST
QUERY_STRING = 
REQUEST_URI = /post.php
REQUEST_TIME = 1366101698

No Post Params.

== Begin post body ==
{"Recent Cases":[{"descript..etc etc"}]}
== End post body ==

有任何想法吗?

4

1 回答 1

0

您可以向以下方法发送一个 url,它会在没有任何标头详细信息的字符串中为您提供响应,因此在您的示例中只有 json.

private static String readUrl(final String urlString) throws Exception {
        BufferedReader reader = null;
        try {
            final URL url = new URL(urlString);
            reader = new BufferedReader(new InputStreamReader(url.openStream()));
            final StringBuffer buffer = new StringBuffer();
            int read;
            final char[] chars = new char[1024];
            while ((read = reader.read(chars)) != -1) {
                buffer.append(chars, 0, read);
            }
            return buffer.toString();
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
    }
于 2013-04-16T12:59:37.860 回答