HttpClient获取返回类型为JSON或XML的数据
Java_HttpClient获取返回类型为JSON或XML的数据
- 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的数据的更多相关文章
- struts2 中的 result 返回类型是 json 的配置问题
struts2 中的 result 返回类型是 json 的配置问题 1.引入包(本文中的包全部引自struts-2.1.8.1\lib): struts2-json-plugin-2.1.8.1.j ...
- json和xml封装数据、数据缓存到文件中
一.APP的通信格式之xml xml:扩展标记语言,可以用来标记数据,定义数据类型,是一种允许用户对自己标记语言进行定义的源语言.XML格式统一,扩平台语言,非常适合数据传输和通信,业界公认的标准. ...
- ASP.NET Web Api返回对象类型为JSON还是XML
在Umbraco平台上开发过程中,我用WebApi返回JSON result给前端 前端使用React调用这个web api来获取JSON result 我写的web api方法是返回JSON 类型的 ...
- SpringMVC——-Controller返回格式化数据如JSON、XML的配置方式和机制
1.本文内容 我们在Web项目开发过程中,一般来说访问一个处理器,然后会返回一个视图,或者跳转到另外的处理器.但是随着项目越来越复杂,需求越来越复杂,对于处理器返回数据的类型要求也越来越多.比如要求能 ...
- Controller接收处理json、xml格式数据
1.RequestBody接收json格式的数据,并直接转为对象. User.java使用lombok依赖包 @Data @AllArgsConstructor @NoArgsConstructor ...
- ajax 另外两种返回类型(json xml)
返回json类型(例子): <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http ...
- ajax返回类型dataType json和text比较
$.ajax({ type: "post", url: "${ctx}/modules/fos/reference/echart", //dataType:'j ...
- SpringMVC常用配置-Controller返回格式化数据如JSON、XML的配置方式和机制
- SUBMIT RM07DOCS【MB51】 获取返回清单,抓取标准报表数据
*&---------------------------------------------------------------------* *& Report YT_SUBMIT ...
随机推荐
- 网络基础 TCP/IP
为了理解 HTTP,我们有必要事先了解一下 TCP/IP 协议族.通常使用的网络(包括互联网)是在 TCP/IP 协议族的基础上运作的.而 HTTP 属于它内部的一个子集.接下来,我们仅介绍理解 HT ...
- oracle之 11.2.0.4 bbed安装
一. bbed安装: 1.ORACLE 11G下安装BBED,需要从ORACLE 10G中复制三个包 sbbdpt.o .ssbbded.o 并将两个文件移到$ORACLE_HOME/rdbms/li ...
- jmeter自动生成报告
从JMeter 3.0开始已支持自动生成动态报告,我们可以更容易根据生成的报告来完成我们的性能测试报告. 如何生成html测试报告 如果未生成结果文件(.jtl),可运行如下命令生成报告: jmete ...
- ES(1): Creat linux VM on Azure
本章记录在ES集群之前的环境准备工作,主要包含的内容如下: 目录: 创建linux虚拟机 启用root用户 创建linux虚拟机 首先创建一个云服务 按向导创建云服务名称,如下 创建虚拟机, 第二步: ...
- BASIC-1_蓝桥杯_闰年判断
正确代码: #include <stdio.h> int main(void){ int year = 0 ; scanf("%d",&year); if (y ...
- bzoj1047 理想的正方形
Description 有一个a*b的整数组成的矩阵,现请你从中找出一个n*n的正方形区域,使得该区域所有数中的最大值和最小值的差最小. Input 第一行为3个整数,分别表示a,b,n的值第二行至第 ...
- 峰Spring4学习(2)依赖注入的几种方式
一.装配一个bean 二.依赖注入的几种方式 com.cy.entity People.java: package com.cy.entity; public class People { pri ...
- 学习笔记之Jira
Jira | Issue & Project Tracking Software | Atlassian https://www.atlassian.com/software/jira The ...
- [UE4]混合动画以及Try Get Pawn Owner、Get Velocity、VectorLength的使用
混合动画,可以混合个多动画之间的动画,多个动画相当于关键帧,关键帧之间可以生成混合出过度动画. 实时动态更新Speed参数. 知识点: 一.可以在蓝图中使用“Try Get Pawn Owner”取得 ...
- javascript cookie操作.
给cookie追加name: document.cookie="name="+escape("我叫钢蛋");//这里可以不写secape,这样写会更加的安全., ...