Android-Httpclient数据解析
最近在做一个联网的小程序,使用httpclient去请求服务器,获得返回数据。
。。。
mResponse = mClient.execute(get);
String charset = EntityUtils.getContentCharSet(mResponse.getEntity());//获得的是utf-8
byte[] bResultXml = EntityUtils.toByteArray(mResponse.getEntity());
String content=new String(bResultXml,charset)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在你发送请求的的时候就要指定编码格式。直接上代码:
public String sendHttpGet(String url, String charset) {
final HttpClient httpClient = new HttpClient();
final GetMethod getMethod = new GetMethod(url);
getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, charset);
getMethod.getParams().setSoTimeout(5000);
getMethod.addRequestHeader("Referer", "http://www.baidu.com");
getMethod.addRequestHeader("User-Agent",
"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.52 Safari/536.5");
String result = null;
// 执行postMethod
int statusCode = 0;
try {
statusCode = httpClient.executeMethod(getMethod);
} catch (HttpException e) {
log.error(e.getMessage());
} catch (IOException e) {
log.error(e.getMessage());
}
if (statusCode == HttpStatus.SC_OK) {
try {
InputStream input = getMethod.getResponseBodyAsStream();
result = inputStream2String(input, charset);
} catch (IOException e) {
e.getMessage();
}
}
getMethod.releaseConnection();
return result;
}
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.examples;
import java.net.Socket;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.DefaultHttpClientConnection;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.params.SyncBasicHttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.protocol.ImmutableHttpProcessor;
import org.apache.http.protocol.RequestConnControl;
import org.apache.http.protocol.RequestContent;
import org.apache.http.protocol.RequestExpectContinue;
import org.apache.http.protocol.RequestTargetHost;
import org.apache.http.protocol.RequestUserAgent;
import org.apache.http.util.EntityUtils;
/**
* Elemental example for executing multiple GET requests sequentially.
* <p>
* Please note the purpose of this application is demonstrate the usage of HttpCore APIs.
* It is NOT intended to demonstrate the most efficient way of building an HTTP client.
*/
public class ElementalHttpGet {
public static void main(String[] args) throws Exception {
HttpParams params = new SyncBasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
HttpProtocolParams.setUseExpectContinue(params, true);
HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
// Required protocol interceptors
new RequestContent(),
new RequestTargetHost(),
// Recommended protocol interceptors
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()});
HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
HttpContext context = new BasicHttpContext(null);
HttpHost host = new HttpHost("localhost", 8080);
DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
try {
String[] targets = {
"/",
"/servlets-examples/servlet/RequestInfoExample",
"/somewhere%20in%20pampa"};
for (int i = 0; i < targets.length; i++) {
if (!conn.isOpen()) {
Socket socket = new Socket(host.getHostName(), host.getPort());
conn.bind(socket, params);
}
BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]);
System.out.println(">> Request URI: " + request.getRequestLine().getUri());
request.setParams(params);
httpexecutor.preProcess(request, httpproc, context);
HttpResponse response = httpexecutor.execute(request, conn, context);
response.setParams(params);
httpexecutor.postProcess(response, httpproc, context);
System.out.println("<< Response: " + response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
System.out.println("==============");
if (!connStrategy.keepAlive(response, context)) {
conn.close();
} else {
System.out.println("Connection kept alive...");
}
}
} finally {
conn.close();
}
}
}
需要手动去指定编码:
EntityUtils.toString(httpResponse.getEntity(),HTTP.UTF_8);
一般请求代码如下:
HttpClient httpclient = new DefaultHttpClient();
HttpPost request = new HttpPost(URL);
StringEntity s = new StringEntity(resqueString, HTTP.UTF_8);
s.setContentType("text/xml charset=utf-8");
request.setEntity(s);
HttpResponse httpResponse=httpclient.execute(request);
return EntityUtils.toString(httpResponse.getEntity(),HTTP.UTF_8
);
andev的回答是关于Client发出请求时就指定编码,但这仅仅是告诉Server,客户端使用什么样的编码,但Server是否支持以相同的编码返回,这要看Server的具体实现了。
由于我们是从Server端接收数据,更应该关注与Server端返回时的协议头。
根据HTTP协议,在Server端返回时,和编解码相关的有如下两个Header
Content-Encoding (Ex:Content-Encoding:gzip)
Content-Type (Ex:Content-Type:text/html; charset=utf-8)
你在解析数据时,
首先得根据Content-Encoding进行编解码
再基于Content-Type的内容指定字符编码
最后,你或许需要关注一下mimetype——“text/html”
当然,你根据上述方式进行处理后,还是是出现乱码,那么可以肯定Server端未按照协议传输数据。
你在处理HTTP协议的内容,建议阅读一下RFC2616文档