Java_HttpClient获取返回类型为JSON或XML的数据

原创 2017年04月06日 17:38:29
  • 706

HttpClient 获取返回类型为JSON或XML的数据

使用httpcomponents-client-4.1.3(下载页面:http://hc.apache.org/httpcomponents-client-ga/download.html 最新是5.20发布的4.2版本)向网页发送HTTP请求抓取数据。

我所调用的服务明确写了他们支持多种类型的返回结果,如下:

The content types we currently support are:

•«text/html»

•«application/xhtml+xml»

•«text/xml»

•«application/json»

若不设置返回类型,每次获取的返回的内容是默认的text/html,而我需要的是更具有信息量的xml或者json。找了很多地方,没有看到设置ContentType的,纠结了一下。。。

其实,最好的教程还是httpclient下载下来自带的例子和pdf,其中examples中就有一个ClientGZipContentCompression.java,它是用来请求获取gzip的数据并解压显示。这个文件稍微改改就可以了。如下是接收json类型。

/ * ==================================================================== */

import java.io.IOException;

import java.io.InputStream;

import java.util.zip.GZIPInputStream;

import org.apache.http.Header;

import org.apache.http.HeaderElement;

import org.apache.http.HttpEntity;

import org.apache.http.HttpException;

import org.apache.http.HttpRequest;

import org.apache.http.HttpRequestInterceptor;

import org.apache.http.HttpResponse;

import org.apache.http.HttpResponseInterceptor;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.entity.HttpEntityWrapper;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.protocol.HttpContext;

import org.apache.http.util.EntityUtils;

public class JsonTest{

public final static void main(String[] args) throws Exception {

DefaultHttpClient httpclient = new DefaultHttpClient();

try {

httpclient.addRequestInterceptor(new HttpRequestInterceptor() {

public void process(

final HttpRequest request,

final HttpContext context) throws HttpException, IOException {

if (!request.containsHeader("Accept-Encoding")) {

request.addHeader("Accept", "application/json");

}

}

});

//            httpclient.addResponseInterceptor(new HttpResponseInterceptor() {

//

//                public void process(

//                        final HttpResponse response,

//                        final HttpContext context) throws HttpException, IOException {

//                    HttpEntity entity = response.getEntity();

//                    Header ceheader = entity.getContentEncoding();

//                    if (ceheader != null) {

//                        HeaderElement[] codecs = ceheader.getElements();

//                        for (int i = 0; i < codecs.length; i++) {

//                            if (codecs[i].getName().equalsIgnoreCase("gzip")) {

//                                response.setEntity(

//                                        new GzipDecompressingEntity(response.getEntity()));

//                                return;

//                            }

//                        }

//                    }

//                }

//

//            });

HttpGet httpget = new HttpGet("http://your_url");

// Execute HTTP request

System.out.println("executing request " + httpget.getURI());

HttpResponse response = httpclient.execute(httpget);

System.out.println("----------------------------------------");

System.out.println(response.getStatusLine());

//            System.out.println(response.getLastHeader("Content-Encoding"));

//            System.out.println(response.getLastHeader("Content-Length"));

System.out.println("----------------------------------------");

HttpEntity entity = response.getEntity();

if (entity != null) {

String content = EntityUtils.toString(entity);

System.out.println(content);

System.out.println("----------------------------------------");

//                System.out.println("Uncompressed size: "+content.length());

}

} finally {

// When HttpClient instance is no longer needed,

// shut down the connection manager to ensure

// immediate deallocation of all system resources

httpclient.getConnectionManager().shutdown();

}

}

//    static class GzipDecompressingEntity extends HttpEntityWrapper {

//

//        public GzipDecompressingEntity(final HttpEntity entity) {

//            super(entity);

//        }

//

//        @Override

//        public InputStream getContent()

//            throws IOException, IllegalStateException {

//

//            // the wrapped entity's getContent() decides about repeatability

//            InputStream wrappedin = wrappedEntity.getContent();

//

//            return new GZIPInputStream(wrappedin);

//        }

//

//        @Override

//        public long getContentLength() {

//            // length of ungzipped content is not known

//            return -1;

//        }

//

//    }

}

HttpClient获取返回类型为JSON或XML的数据的更多相关文章

  1. struts2 中的 result 返回类型是 json 的配置问题

    struts2 中的 result 返回类型是 json 的配置问题 1.引入包(本文中的包全部引自struts-2.1.8.1\lib): struts2-json-plugin-2.1.8.1.j ...

  2. json和xml封装数据、数据缓存到文件中

    一.APP的通信格式之xml xml:扩展标记语言,可以用来标记数据,定义数据类型,是一种允许用户对自己标记语言进行定义的源语言.XML格式统一,扩平台语言,非常适合数据传输和通信,业界公认的标准. ...

  3. ASP.NET Web Api返回对象类型为JSON还是XML

    在Umbraco平台上开发过程中,我用WebApi返回JSON result给前端 前端使用React调用这个web api来获取JSON result 我写的web api方法是返回JSON 类型的 ...

  4. SpringMVC——-Controller返回格式化数据如JSON、XML的配置方式和机制

    1.本文内容 我们在Web项目开发过程中,一般来说访问一个处理器,然后会返回一个视图,或者跳转到另外的处理器.但是随着项目越来越复杂,需求越来越复杂,对于处理器返回数据的类型要求也越来越多.比如要求能 ...

  5. Controller接收处理json、xml格式数据

    1.RequestBody接收json格式的数据,并直接转为对象. User.java使用lombok依赖包 @Data @AllArgsConstructor @NoArgsConstructor ...

  6. ajax 另外两种返回类型(json xml)

    返回json类型(例子): <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http ...

  7. ajax返回类型dataType json和text比较

    $.ajax({ type: "post", url: "${ctx}/modules/fos/reference/echart", //dataType:'j ...

  8. SpringMVC常用配置-Controller返回格式化数据如JSON、XML的配置方式和机制

  9. SUBMIT RM07DOCS【MB51】 获取返回清单,抓取标准报表数据

    *&---------------------------------------------------------------------* *& Report YT_SUBMIT ...

随机推荐

  1. k最邻近算法——使用kNN进行手写识别

    上篇文章中提到了使用pillow对手写文字进行预处理,本文介绍如何使用kNN算法对文字进行识别. 基本概念 k最邻近算法(k-Nearest Neighbor, KNN),是机器学习分类算法中最简单的 ...

  2. Java使用Unsafe接口操作数组Demo

    public class unSafeArrayDemo { private static final sun.misc.Unsafe UNSAFE; private static final lon ...

  3. 【转】每天一个linux命令(4):mkdir命令

    原文网址:http://www.cnblogs.com/peida/archive/2012/10/25/2738271.html linux mkdir 命令用来创建指定的名称的目录,要求创建目录的 ...

  4. MyBatis持久层框架使用总结 转载

    MyBatis持久层框架使用总结   MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google co ...

  5. Android 禁止系统进入深度休眠

    在Linux系统中,wake_lock是一直锁机制,只要有驱动占用这个锁,系统就不会进入深度休眠. 获取此锁的方法有两种: 1.在adb中通过指令获取wake_lock,系统就不会进入深度休眠 ech ...

  6. 加快QT工程编译速度

    转载:学海方舟 利用Qt Creator编译工程大家都觉得慢,特别是整个工程重新编译时,那问题来了怎么加快编译速度呢 ,其实方法很简单,利用我们的强大的多核CPU来实现多核编译: 在编译参数中加入“- ...

  7. jenkins 执行python脚本 断言失败就可以构建失败

    可以配合try: 那个语句去搭配

  8. appium--每次启动会重新安装的问题(没试过)

    有人说加这个 最后 大神说 在appium哪里就可以设置了  对,第一个不勾选就不会安装了[经理][Java]大连●Messi_Z(726862194)  15:54:10把这些东西全去掉就好了

  9. 9-16Jenkins-4节点

    1.Jenkins-系统管理-全局安全配置,设置代理端口和协议类型,保存 2.Jenkins-系统管理-节点管理,建立节点 设置节点名称,节点工作目录.标签.用法.启动方式设置如下: 标签用于管理节点 ...

  10. var abc = function(x){} 和 function abc(x){}的区别

    转自百度知道. 问:js里声明函数有几种方式? var abc = function(x){} 和 function abc(x){} 这两种声明方法有什么不同? 答:首先后者是指函数声明,前者是指函 ...