Android-Httpclient数据解析

发布于 2016-11-29 18:30:33 字数 347 浏览 1322 评论 4

最近在做一个联网的小程序,使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

偏爱自由 2017-08-14 11:53:51

在你发送请求的的时候就要指定编码格式。直接上代码:

 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;
}

想挽留 2017-04-16 05:59:28

 /*
* ====================================================================
* 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();
}
}

}

灵芸 2017-02-05 06:42:18

需要手动去指定编码:

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

);

清晨说ぺ晚安 2017-01-07 03:54:03

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文档

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文