HttpClient_002_中文亂碼、HttpClient中文亂碼透析、總結

 

中文亂碼原理代碼:html

 String s = "中文";
        byte[] bs2 = s.getBytes("utf-8");//將s拆成:utf-8個體,注:utf-8指s本來就是utf-8
        String s1 = new String(bs2,"iso-8859-1");//將bs2組裝成:iso-8859-1串
        String s2 = new String(bs2,"utf-8");//將bs2組裝成:utf-8串
        String s3 = new String(s1.getBytes("iso-8859-1"),"utf-8");//將s1拆成iso-8859-1串,而後組裝成utf-8
        System.out.println(s1+"\n"+s2+"\n"+s3);

結果:java

??????
中文
中文

 

實例源碼下載:http://download.csdn.net/detail/poiuy1991719/8594485

 

解決HttpClient中文亂碼,項目演示:web

1:編寫httpClient_001apache

所需包:網絡

一、1:編寫URLUtil類session

package com.west.test.httpclient;

public class URLUtil {
    public static final String HttpClient_002="http://localhost:8080/httpClient_002/";//訪問本地項目2路徑
    public static final String POST_CONTENT=HttpClient_002+"PostContent";
}

一、2:編寫Servlet類app

package com.west.test.httpclient;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import javax.servlet.ServletException;

public class PostServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        System.out.println("========httpClient_001 PostServlet start=========");
        System.out.println("httpClient_001:doPost方式提交");
        HttpClient httpClient = new HttpClient();
        PostMethod method = new PostMethod(URLUtil.POST_CONTENT);
//         解決中文亂碼(設置:"我方"HttpClient提交、解析所用碼)
        method.getParams().setContentCharset("utf-8");
        
        String charset=method.getParams().getContentCharset();
        NameValuePair name = new NameValuePair("name", "張三");
        NameValuePair password = new NameValuePair("password",
                "password:123321");
        method.setRequestBody(new NameValuePair[] { name, password });
        String rt = "";
        try {
            int status = httpClient.executeMethod(method);
            if (status == HttpStatus.SC_OK) {
                rt = method.getResponseBodyAsString();
                System.out.println("httpClient_001獲得:" + rt);
                codeTest(rt,charset);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("網絡鏈接失敗,請聯繫管理員!");
        }
        // 釋放HttpClient資源
        method.releaseConnection();
        outMessage(response, rt);

    }

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        System.out.println("httpClient_001:doGet方式提交");
        doPost(request, response);

    }

    public void outMessage(HttpServletResponse response, String message) {
        try {
//             解決"界面"中文亂碼(設置:"我方"提交所用碼、"對方"解析所用碼)
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.print(message);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void codeTest(String rt ,String charset) throws Exception {
        
        System.out.println("獲得的是:"+charset);
        byte[] btr=rt.getBytes(charset);
        String rt01 = new String(btr, "iso-8859-1");
        System.out.println("String(btr,'iso-8859-1')轉碼01:" + rt01);
        String rt02 = new String(btr, "utf-8");
        System.out.println("String(btr,'utf-8')轉碼02:" + rt02);
        String rt03 = new String(rt01.getBytes("iso-8859-1"), "utf-8");
        System.out.println(rt03);
        
    }
}

1.3:配置web.xmljsp

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.5"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 <display-name>test</display-name>
 
  <servlet>
    <servlet-name>PostServlet</servlet-name>
    <servlet-class>com.west.test.httpclient.PostServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>PostServlet</servlet-name>
    <url-pattern>/PostServlet</url-pattern>
  </servlet-mapping>
 
 <session-config>
  <session-timeout>600</session-timeout>
 </session-config>
 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
</web-app>

一、3:編寫界面:index.jspide

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
<head>
<title>test</title>
</head>
<body>
    <form action="PostServlet" method="post">
        <input type="submit" value="Post提交">
    </form>
</body>
</html>

 

 

2:編寫項目:httpClient_002post

二、1:編寫Servlet類

package com.test.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class PostContent extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        System.out.println("=========httpClient_002 PostContent start============");
        System.out.println("httpClient_002:doPost方式執行");
//        解決中文亂碼(設置:"我方"解析所用碼)
        request.setCharacterEncoding("utf-8");
        
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        System.out.println("httpClient_002獲得:{name:" + name+",password:"+password+"}");
        String reStr = "{name=" + name + ",password="
                + password+"}";
        outMessage(response, reStr);
    }

    public void outMessage(HttpServletResponse response, Object message) {
        try {
//            解決中文亂碼(設置:"我方"提交所用碼,"httpClient_001"解析所用碼)
            response.setContentType("text/html;charset=utf-8");
            
            PrintWriter out = response.getWriter();
            out.print(message);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2.2:配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.5"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 <display-name>test002</display-name>
 
  <servlet>
    <servlet-name>PostContent</servlet-name>
    <servlet-class>com.test.servlet.PostContent</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>PostContent</servlet-name>
    <url-pattern>/PostContent</url-pattern>
  </servlet-mapping>
 
 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
  <welcome-file>default.html</welcome-file>
 </welcome-file-list>
</web-app>

3:總結

一、解決中文亂碼(設置:"我方"HttpClient提交、解析所用碼)
   method.getParams().setContentCharset("utf-8");

二、解決"界面"中文亂碼(設置:"我方"提交所用碼、"對方"解析所用碼)
   response.setContentType("text/html;charset=utf-8");

三、解決中文亂碼(設置:"我方"解析所用碼)
   request.setCharacterEncoding("utf-8");

四、解決中文亂碼(設置:"我方"提交所用碼、"httpClient_001"解析所用碼),同2
   response.setContentType("text/html;charset=utf-8");

 

 

附加:

請求網頁、servlet:

GetMethod getMethod = new GetMethod("http://www.baidu.com");  
//(1)、這裏能夠設置本身想要的編碼格式
getMethod.getParams().setContentCharset("utf-8"); 
 
//(2)、對於get方法也能夠這樣設置 
getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"GB2312");  
 
//(3)、還能夠以下這樣設置
getMethod.addRequestHeader("Content-Type", "text/html; charset=UTF-8");  
  
//(4)、固然一樣能夠直接設置 httpClient 對象的編碼格式
HttpClient httpClient = new HttpClient();
httpClient.getParams().setContentCharset("utf-8");
 
//使用流的方式讀取也能夠以下設置
InputStream in = getMethod.getResponseBodyAsStream();  
//這裏的編碼規則要與上面的相對應  
BufferedReader br = new BufferedReader(new InputStreamReader(in,"utf-8"));

請求方法、servlet:

PostMethod PostMethod= new PostMethod("http://localhost:8080/ezid-cert-mobile/upload");
//(1)、一般能夠以下設置本身想要的編碼格式
postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");
 
//(2)、也重載PostMethod的getRequestCharSet()方法
public  class UTF8PostMethod extends PostMethod{
    public UTF8PostMethod(String url){
        super(url);
    }
    @Override
    public String getRequestCharSet() {
     return "UTF-8";
    }
}
 
//(3)、若是是方法的參數出現亂碼問題,那麼你能夠以下設置參數
Charset utf8Charset = Charset.forName("UTF-8");
multipartContent.addPart("name", new StringBody(Info.getUserEntity().getName(), utf8Charset));
 
//(4)、若是你用的是Part [] parts={...}傳參方式的話能夠以下設置
StringPart name=new StringPart("name",certFormEntity.getPersonName(), "UTF-8");
相關文章
相關標籤/搜索