問題描述:
用戶那邊使用httpClien的方式進行post請求,但是這我們這段進行接收數據解析的時候發現解析後的中文出現亂碼(????),試了好幾種方式都不行,通過查找資料,測試,終於ok了
解決方法:
httpClien發送post請求方式:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
public class Test {
public static void main(String[] args) throws Exception {
String xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><Request><UserName>富貴</UserName><LoginName>test4</LoginName><UserId>123150</UserId><PaperType>1</PaperType><PaperNo>310109199307143011</PaperNo><OrgId>00001</OrgId><MobileTelephone>11111111111</MobileTelephone></Request>";
String resurl = "http://192.168.212.108:8080/wtp/platform/wlj/AddUserInfo.do";
//創建httpclient工具對象
HttpClient client = new HttpClient();
//創建post請求方法
PostMethod myPost = new PostMethod(resurl);
//剛開始沒有添加這個設置,接收解析數據時,用了好多種方法都是亂碼,httClien發送請求這邊加上這個設置,中文解析正常
myPost.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
//設置請求超時時間
client.setConnectionTimeout(3000*1000);
String responseString = null;
try{
//設置請求頭部類型
myPost.setRequestHeader("Content-Type","application/xml");
myPost.setRequestHeader("charset","UTF-8");
//設置請求體,即xml文本內容,一種是直接獲取xml內容字符串,一種是讀取xml文件以流的形式
myPost.setRequestBody(xmlString);
int statusCode = client.executeMethod(myPost);
//只有請求成功200了,才做處理
if(statusCode == HttpStatus.SC_OK){
InputStream inputStream = myPost.getResponseBodyAsStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
StringBuffer stringBuffer = new StringBuffer();
String str = "";
while ((str = br.readLine()) != null) {
stringBuffer.append(str);
System.out.println(str);
}
responseString = stringBuffer.toString();
}
}catch (Exception e) {
e.printStackTrace();
}finally{
myPost.releaseConnection();
}
}
}
接收請求並解析請求方式(返回解析後得到的字符串):
public static String getInputData(HttpServletRequest request) throws IOException{
request.setCharacterEncoding("UTF-8");
InputStream inputStream = request.getInputStream();
String result = null;
try {
ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
outSteam.write(buffer, 0, len);
}
outSteam.close();
inputStream.close();
result = new String(outSteam.toByteArray(), "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return result;
}