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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM