Android-Httpclient数据解析

需求定制 需求定制 主题:1050 回复:2283

Android-Httpclient数据解析

虐人心 发布于 2016-11-29 字数 383 浏览 1171 回复 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)

发布评论

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

支持 Markdown 语法,需要帮助?

评论(4

偏爱自由 2017-08-14 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;
}
想挽留 2017-04-16 3 楼

 /*

  • ====================================================================
  • 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/&gt;.
  • */

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 &lt; 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("&gt;&gt; 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("&lt;&lt; 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 2 楼

需要手动去指定编码:

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 1 楼

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