问题描述:
用户那边使用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;
}