webservice

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
*webservice
*/
public class UrlDemo {


public static void callXml(String word) throws Exception{
//地址
URL url = new URL("http://www.webxml.com.cn/WebServices/TranslatorWebService.asmx");
//调用的方法
// String soapActionString = "http://WebXml.com.cn/getEnCnTwoWayTranslator";

//打开链接
HttpURLConnection con = (HttpURLConnection) url.openConnection();

//拼接好xml
StringBuffer sb = new StringBuffer();
String xmlStr = sb.toString();
System.out.println(xmlStr);
//设置好header信息
con.setRequestMethod("POST");
con.setRequestProperty("content-type", "text/xml; charset=utf-8");
con.setRequestProperty("Content-Length", String.valueOf(xmlStr.getBytes().length));
// con.setRequestProperty("soapActionString", soapActionString);

//post请求需要设置
con.setDoOutput(true);
con.setDoInput(true);

//对请求body 往里写xml 设置请求参数
OutputStream ops = con.getOutputStream();
ops.write(xmlStr.getBytes());
ops.flush();
ops.close();

//设置响应回来的信息
InputStream ips = con.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int length = 0;
while( (length = ips.read(buf)) != -1){
baos.write(buf, 0, length);
baos.flush();
}
byte[] responsData = baos.toByteArray();
baos.close();

//处理写响应信息
String responsMess = new String(responsData,"utf-8");
System.out.println(responsMess);
System.out.println(con.getResponseCode());
}

}

posted @ 2019-09-19 09:38  pretty flower  阅读(147)  评论(0编辑  收藏  举报