java soap提交数据时乱码有关问题
java soap提交数据时乱码问题
在一个项目中,要用java访问.net写的web service。有一个功能是修改用户资料,这就涉及到数据的提交处理。
遇到提交数据时中文乱码问题。原先代码如下的:
String SOAPUrl= BaseUrl.baseUrl+"ProfileService.asmx?op=GetMemberInfoByCardNo"; String SOAPAction = "..................................................."; String xml="............."这里省略生成的xml字符串; System.out.println(xml); URL url = new URL(SOAPUrl); URLConnection connection = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) connection; // Set the appropriate HTTP parameters. httpConn.setRequestProperty( "Content-Length",String.valueOf( xml.length())); httpConn.setRequestProperty("Content-Type","text/xml; charset=utf-8"); httpConn.setRequestProperty("SOAPAction",SOAPAction); httpConn.setRequestMethod( "POST" ); httpConn.setDoOutput(true); httpConn.setDoInput(true); // Everything's set up; send the XML that was read in to b. OutputStream out = httpConn.getOutputStream(); PrintWriter writer=new PrintWriter(out); osw.write(xml); osw.flush();
修改一下代码,如下:
String SOAPUrl= BaseUrl.baseUrl+"/ProfileService.asmx?op=GetMemberInfoByCardNo"; String SOAPAction = "..................................................."; String xml=".......................";这里省略生成的xml字符串 System.out.println(xml); URL url = new URL(SOAPUrl); URLConnection connection = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) connection; // Set the appropriate HTTP parameters. httpConn.setRequestProperty( "Content-Length",String.valueOf( xml.length())); httpConn.setRequestProperty("Content-Type","text/xml; charset=utf-8"); httpConn.setRequestProperty("SOAPAction",SOAPAction); httpConn.setRequestMethod( "POST" ); httpConn.setDoOutput(true); httpConn.setDoInput(true); // Everything's set up; send the XML that was read in to b. OutputStream out = httpConn.getOutputStream(); OutputStreamWriter osw=new OutputStreamWriter(out,"utf-8"); //PrintWriter writer=new PrintWriter(out); osw.write(xml); osw.flush();
注意红色粗体部份。将原先的PrintWriter换成OutputStreamWriter,并在构造OutputStreamWriter实例时,用上"utf-8"编码(我的项目中是用utf-8)