Android,HTTP请求中文乱码

// 编码参数
            List<NameValuePair> formparams = new ArrayList<NameValuePair>(); // 请求参数
            for (NameValuePair p : params) {
                formparams.add(p);
            }
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams,HTTP.UTF_8);
            // 创建POST请求
            HttpPost request = new HttpPost(url);
            request.setEntity(entity);
Android发送HTTP请求,android默认编码已是utf-8。
问题描述:
如上代码中已经设置了请求为UTF-8,服务器中编码也是全部UTF-8,可是服务器获取中文还是出现乱码。
由于服务器端并非自己开发,无法看到服务器是如何运行的,只知道编码是UTF-8。
同样的服务器,IPHONE客户端发送中文无乱码。

问题解决:
尝试打印Andorid,IPHONE的HTTP头。
发现其中的content-type 不一样。
Andorid :content-type:application/x-www-form-urlencoded;
IPHONE:content-type:application/x-www-form-urlencoded; charset=utf-8

于是尝试在请求的时候加个头
request.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");

然后问题解决。

1.创建HttpGet或HttpPost对象,将要请求的URL通过构造方法传入HttpGet或HttpPost对象。

2.使用DefaultHttpClient类的execute方法发送HTTP GET或HTTP POST请求,并返回HttpResponse对象。

3.通过HttpResponse接口的getEntity方法返回响应信息,并进行相应的处理。

如果使用HttpPost方法提交HTTP POST请求,还需要使用HttpPost类的setEntity方法设置请求参数。

本例使用了两个按钮来分别提交HTTP GET和HTTP POST请求,并从EditText组件中获得请求参数(bookname)值,最后将返回结果显示在TextView组件中。两个按钮共用一个onClick事件方法,代码如下:

public void onClick(View view)  

{  

    //  读者需要将本例中的IP换成自己机器的IP  

    String url = "http://192.168.17.81:8080/querybooks/QueryServlet";  

    TextView tvQueryResult = (TextView) findViewById(R.id.tvQueryResult);  

    EditText etBookName = (EditText) findViewById(R.id.etBookName);  

    HttpResponse httpResponse = null;  

    try  

    {  

        switch (view.getId())  

        {  

            //  提交HTTP GET请求  

            case R.id.btnGetQuery:  

                //  向url添加请求参数  

                url += "?bookname=" + etBookName.getText().toString();  

                //  第1步:创建HttpGet对象  

                HttpGet httpGet = new HttpGet(url);  

                //  第2步:使用execute方法发送HTTP 
GET请求,并返回HttpResponse对象  

                httpResponse = new DefaultHttpClient().execute(httpGet);  

                //  判断请求响应状态码,状态码为200表
示服务端成功响应了客户端的请求  

                if (httpResponse.getStatusLine().
getStatusCode() == 200)  

                {  

                    //  第3步:使用getEntity方法获得返回结果  

                    String result = EntityUtils.
toString(httpResponse.getEntity());  

                    //  去掉返回结果中的"\r"字符,
否则会在结果字符串后面显示一个小方格  

                    tvQueryResult.setText(result.replaceAll("\r", ""));  

                }  

                break;  

            //  提交HTTP POST请求  

            case R.id.btnPostQuery:  

                //  第1步:创建HttpPost对象  

                HttpPost httpPost = new HttpPost(url);  

                //  设置HTTP POST请求参数必须用NameValuePair对象  

                List<NameValuePair> params = new 
ArrayList<NameValuePair>();  

                params.add(new BasicNameValuePair
("bookname", etBookName.getText(). toString()));  

                //  设置HTTP POST请求参数  

                httpPost.setEntity(new 
UrlEncodedFormEntity(params, HTTP.UTF_8));  

                //  第2步:使用execute方法发送HTTP 
POST请求,并返回HttpResponse对象  

                httpResponse = new DefaultHttpClient().
execute(httpPost);  

                if (httpResponse.getStatusLine().
getStatusCode() == 200)  

                {  

                    //  第3步:使用getEntity方法获得返回结果  

                    String result = EntityUtils.toString
(httpResponse.getEntity());  

                    //  去掉返回结果中的"\r"字符,
否则会在结果字符串后面显示一个小方格  

                    tvQueryResult.setText(result.replaceAll("\r", ""));  

                }  

                break;  

        }  

    }  

    catch (Exception e)  

    {  

        tvQueryResult.setText(e.getMessage());  

    }  

import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.util.Log;

public class RequestByHttpPost {

 public static String TIME_OUT = "操作超时";
 
 public static String doPost(List<NameValuePair> params,String url) throws Exception{
  String result = null;
      // 新建HttpPost对象
      HttpPost httpPost = new HttpPost(url);
      // 设置字符集
      HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
      // 设置参数实体
      httpPost.setEntity(entity);
      // 获取HttpClient对象
      HttpClient httpClient = new DefaultHttpClient();
      //连接超时
      httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
      //请求超时
      httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);
      try {
       // 获取HttpResponse实例
          HttpResponse httpResp = httpClient.execute(httpPost);
          // 判断是够请求成功
          if (httpResp.getStatusLine().getStatusCode() == 200) {
           // 获取返回的数据
           result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
           Log.i("HttpPost", "HttpPost方式请求成功,返回数据如下:");
           Log.i("result", result);
          } else {
           Log.i("HttpPost", "HttpPost方式请求失败");
          }
      } catch (ConnectTimeoutException e){
       result = TIME_OUT;
      }
     
      return result;
 }
}

 

protected static CommResult HttpPost(Context context, String url,
   HashMap<String, String> map) {
  synchronized ("http post") {
   CommResult result = new CommResult();

   HttpClient httpClient = getNewHttpClient(context);

   HttpPost httpPost = new HttpPost(url);

   ArrayList<BasicNameValuePair> postDate = new ArrayList<BasicNameValuePair>();

   Set<String> set = map.keySet();

   Iterator<String> iterator = set.iterator();

   while (iterator.hasNext()) {
    String key = (String) iterator.next();
    postDate.add(new BasicNameValuePair(key, map.get(key)));

   }
   try {
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
      postDate, HTTP.UTF_8);
    httpPost.setEntity(entity);
    HttpResponse response = httpClient.execute(httpPost);

    InputStream in = response.getEntity().getContent();
    int statusCode = response.getStatusLine().getStatusCode();
    String message = InputStreamToString(in);

    result.setMessage(message);
    result.setResponseCode(String.valueOf(statusCode));

   } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
   } catch (ClientProtocolException e) {
    e.printStackTrace();
   } catch (IOException e) {
    e.printStackTrace();
   }

   return result;
  }
 }


本篇文章来源于 Linux公社网站(www.linuxidc.com)  原文链接:http://www.linuxidc.com/Linux/2013-03/80178.htm

public Map<String, Object> CreateNote(int albumId, String title,
  String remark) {
 String noteId = "";
 Map<String, Object> map = new HashMap<String, Object>();
 try {
  HttpParams parms = new BasicHttpParams();
  parms.setParameter("charset", HTTP.UTF_8);
                HttpConnectionParams.setConnectionTimeout(parms, 8 * 1000);
                HttpConnectionParams.setSoTimeout(parms, 8 * 1000);
  HttpClient httpclient = new DefaultHttpClient(parms);
  HttpPost httppost = new HttpPost(ConfigHelper.CreateUri);
  httppost.addHeader("Authorization", mToken);
  httppost.addHeader("Content-Type", "application/json");  
  httppost.addHeader("charset", HTTP.UTF_8);

  JSONObject obj = new JSONObject();
  obj.put("title", title);
  obj.put("categoryId", mCategoryId);
  obj.put("sourceUrl", GetSourceUri());

  JSONArray arr = new JSONArray();

  arr.put(DateFormat.format("yyyyMM",Calendar.getInstance(Locale.CHINA)));  
  obj.put("tags", arr);
  obj.put("content", remark); 
  httppost.setEntity(new StringEntity(obj.toString(), HTTP.UTF_8));
  HttpResponse response;
  response = httpclient.execute(httppost);
  int code = response.getStatusLine().getStatusCode();
  if (code == ConstanDefine.ErrorCode.SuccOfHttpStatusCode) {
   String rev = EntityUtils.toString(response.getEntity());
   obj = new JSONObject(rev);
   noteId = obj.getString("id");
   map.put("return_code", "0");
   map.put("content", rev);   
  }
 } catch (Exception e) {
  if (map.containsKey("return_code")) {
   map.remove("return_code");
  }
  map.put("return_code", "1");  
 }
 return map;
}

posted @ 2013-04-03 09:17  ggzjj  阅读(9860)  评论(0编辑  收藏  举报