您的位置:首页 > 理论基础 > 计算机网络

JAVA中使用HttpURLConnection发送XML参数乱码问题

2017-03-08 10:20 706 查看
POST方法

public static String post(String content,String httpUrl){
String result = "";
HttpURLConnection httpURLConnection = null;
ByteArrayOutputStream outputStream = null;
InputStream in = null;
try{
URL url = new URL(httpUrl);
httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setInstanceFollowRedirects(true);
httpURLConnection.setConnectTimeout(3 * 1000);
httpURLConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
httpURLConnection.getOutputStream().write(content.getBytes());
httpURLConnection.getOutputStream().flush();
outputStream=new ByteArrayOutputStream();
in = httpURLConnection.getInputStream();
int len =0;
byte[] bt=new byte[1024];

while((len=in.read(bt))!=-1){
outputStream.write(bt, 0, len);
}
outputStream.flush();
byte[] data=outputStream.toByteArray();
result=new String(data,"utf-8");
} catch (MalformedURLException e) {
result = "error";
} catch (ProtocolException e) {
result = "error";
} catch (IOException e) {
e.printStackTrace();
result = "error";
}finally{
if(in!=null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
result = "error";
}
}
if(outputStream!=null){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
result = "error";
}
}
}
return result;
}
}


调用

public static void main(String[] args){
String httpUrl = "localhost:8080/***/***"
String logistics_interface =
"<request>"
+"<receiverProv>230000"//省
+"</receiverProv>"
+"<receiverCity>231000"//市
+"</receiverCity>"
+"<receiverCounty>231084"//区县
+"</receiverCounty>"
+"<receiverAddress>此处是中文需要进行编码"//地址
+"</receiverAddress>"
+"<receiverLongitude>46.123"//经纬度
+"</receiverLongitude>"
+"<receiverLatitude>46.123"
+"</receiverLatitude>"
+"<startPage>1"//页码数
+"</startPage>"
+"<rowNum>10"//每页条目数
+"</rowNum>"
+"</request>";
String data_digest = getStationQueryXML(logistics_interface);
String customer_code = "customer123"; //客户编码
//如果xml里面存在汉字 一定要在参数传递之前 进行编码
String urlEncoder = URLEncoder.encode(logistics_interface,"utf-8");
String result = post("logistics_interface="+urlEncoder+"&data_digest="+data_digest+"&customer_code="+customer_code,httpUrl);
System.out.println(data_digest);
System.out.println(result);
}


如果xml里面含有中文。需要在传送之前进行URLEncoder.encode(param,”utf-8”) 进行编码。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  乱码 java xml
相关文章推荐