【问题标题】:How to get full json response using httprequest如何使用 httprequest 获得完整的 json 响应
【发布时间】:2016-10-28 09:46:56
【问题描述】:

我只是想点击网址,即 www.google.com 我想捕获整个json响应作为输出...... 我尝试了多个代码来帮助我只找到响应代码,但我想要完整的 json 响应,我可以从中过滤一些信息。

我正在为网络做的事情..

【问题讨论】:

  • 我没有完全明白您需要做什么:您想将 http 响应转换为 json 字符串,还是只想捕获 json 格式的 http 响应?
  • 是的..当我们点击任何 url 时,它会响应 json response ,所以我想得到这些 json 响应。 ...
  • 搜索“如何用java发送请求”

标签: java json parsing httprequest httpresponse


【解决方案1】:

我使用了 ApacheHttpClient jar(版本 4.5.1)。您还需要 HttpCore 库(我使用的是 4.4.3)和其他一些 apache 库(如编解码器)。

这里有一个 GET 方法和一个 POST 方法:

public static String getJsonStringHttpGet(String url,Map<String,String> headers) throws IOException {

        BasicCookieStore cookieStore = new BasicCookieStore();

        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultCookieStore(cookieStore)
        .build();

        HttpCoreContext localContext = new HttpCoreContext();


        HttpGet get = new HttpGet(url);


        /*
         * if you need to specify headers
         */
        if (headers != null) {
            for (String name : headers.keySet()) {
                get.addHeader(name, headers.get(name));
            }
        }



        HttpResponse response = httpClient.execute(get, localContext);



        byte [] bytes = EntityUtils.toByteArray(response.getEntity());


        return new String(bytes);

    }

public static String getJsonStringHttpPost(String url,Map<String,String> postParams,Map<String,String> headers) throws IOException {

        BasicCookieStore cookieStore = new BasicCookieStore();

        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultCookieStore(cookieStore)
        .build();

        HttpCoreContext localContext = new HttpCoreContext();


        HttpPost post = new HttpPost(url);

        /*
         * adding some POST params
         */
        if (postParams != null && postParams.size() > 0) {

            List<BasicNameValuePair> postParameters = new ArrayList<>();

            for (String name : postParams.keySet()) {
                postParameters.add(new BasicNameValuePair(name, postParams.get(name)));
            }

            post.setEntity(new UrlEncodedFormEntity(postParameters));
        }

        /*
         * if you need to specify headers
         */
        if (headers != null) {
            for (String name : headers.keySet()) {
                post.addHeader(name, headers.get(name));
            }
        }



        HttpResponse response = httpClient.execute(post, localContext);



        byte [] bytes = EntityUtils.toByteArray(response.getEntity());


        return new String(bytes);

    }

然后就可以任意解析json字符串了。

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    • 2019-03-16
    • 1970-01-01
    • 2018-06-27
    • 1970-01-01
    相关资源
    最近更新 更多