通过UrlConnection调用Webservice服务
package com.lvshitech.url;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* 通过UrlConnection调用Webservice服务
*/
public class UrlConnection {
public static void main(String[] args) throws IOException {
// 服务的地址
URL url = new URL("http://127.0.0.1:6789/hello");
// 打开链接
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
// 可读可写,请求方式,请求类型
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
// 输出
OutputStream outputStream = httpURLConnection.getOutputStream();
String soap = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ "xmlns:q0=\"http://webservice.lvshitech.com/\""
+ "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
+ "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
+ "<soapenv:Body><q0:sayHello><arg0>"
+ "Peter"
+ "</arg0></q0:sayHello></soapenv:Body></soapenv:Envelope>";
outputStream.write(soap.getBytes());
// 输入
InputStream inputStream = httpURLConnection.getInputStream();
byte []input = new byte[1024];
int len = 0;
String readStr = "";
while((len=inputStream.read(input)) != -1) {
readStr += new String(input, 0, len, "UTF-8");
}
System.out.println(readStr);
// 关闭流
inputStream.close();
outputStream.close();
httpURLConnection.disconnect();
}
}
报错:
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 500 for URL: http://127.0.0.1:6789/hello at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1626) at com.lvshitech.url.UrlConnection.main(UrlConnection.java:34)
原因:
请求头有错,xmlns:节点前漏了空格
补上空格:

在运行:
输出:
<?xml version="1.0" ?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><ns2:sayHelloResponse xmlns:ns2="http://webservice.lvshitech.com/"><return>Hello Peter</return></ns2:sayHelloResponse></S:Body></S:Envelope>

浙公网安备 33010602011771号