http post请求(soap协议)webservice

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
public class Test {
public static void translate(String word) throws Exception {
String urlString = "xxxxx.asmx";
String soapActionString = "xxxx";
URL url = new URL(urlString);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
String soap = "\n" +
" + " xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">\n"
+" \n" +
// soapAction
" <此处为action名称 xmlns="此处为soapAction路径">\n" +
" " + word + "\n" +
" " + 1 + "\n" +
" \n" +
"
\n" +
"
";
byte[] buf = soap.getBytes(Charset.forName("UTF-8"));
httpConn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
httpConn.setRequestProperty("Content-Length", String.valueOf(buf.length));
httpConn.setRequestProperty("soapActionString", soapActionString);
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
OutputStream out = httpConn.getOutputStream();
out.write(buf);
out.close();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK)
{
InputStreamReader is = new InputStreamReader(httpConn.getInputStream());
BufferedReader in = new BufferedReader(is);
String inputLine;
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("zz.xml")));
while ((inputLine = in.readLine()) != null)
{
System.out.println(inputLine);
bw.write(inputLine);
bw.newLine();
}
bw.close();
in.close();
}
else {
InputStream is = httpConn.getErrorStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader in = new BufferedReader(isr);
String inputLine;
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("result.xml")));
while ((inputLine = in.readLine()) != null)
{
System.out.println(inputLine);
bw.write(inputLine);
bw.newLine();
bw.close();
}
in.close();
}
httpConn.disconnect();
}

public static void main(String[] args) throws Exception {
    translate("北京");
}

}

你可能感兴趣的:(http post请求(soap协议)webservice)