首页 > 编程知识 正文

JAVA Webservice接口 调用不成功,返回 500

时间:2023-05-06 11:41:06 阅读:197662 作者:1772

最近Java后台使用HttpURLConnection 调用webservice接口时,返回500错误,代码如下(URL/SOAPAction等使用的假数据)

public void callInterface() throws IOException{try {//第一步:创建服务地址URL url = new URL("http://XXXX/Portal/WebServices/XXX.asmx?wsdl");//第二步:打开一个通向服务地址的连接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //第三步:设置参数 //3.1发送方式设置:POST必须大写 connection.setRequestMethod("POST"); //3.2设置数据格式:content-type connection.setRequestProperty("content-type", "text/xml;charset=UTF-8"); connection.setRequestProperty("SOAPAction", "actionName"); //3.3设置输入输出,因为默认新创建的connection没有读写权限, connection.setDoInput(true); connection.setDoOutput(true); //第四步:组织SOAP数据,发送请求 String soapXML = getXML();//请求XML System.out.println(soapXML); //将信息以流的方式发送出去 connection.connect(); OutputStream os = connection.getOutputStream(); os.write(soapXML.getBytes("UTF-8")); os.flush(); os.close(); //第五步:接收服务端响应,打印 int responseCode = connection.getResponseCode(); if(200 == responseCode){//表示服务端响应成功 //获取当前连接请求返回的数据流 InputStream is = connection.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); String temp = null; while(null != (temp = br.readLine())){ sb.append(temp); } /** * 打印结果 */ System.out.println(sb.toString()); is.close(); isr.close(); br.close(); } os.close();} catch (MalformedURLException e) {e.printStackTrace();}}

 

接口没调成功,调试发现在第五步返回的responseCode 为500

//第五步:接收服务端响应,打印 int responseCode = connection.getResponseCode();

在使用SoapUI测试时,调用接口正常。后在SoapUI上发现,原来SOAPAction这里默认加了一段前缀http://tempuri.org/,如下图

加上后缀后调用接口成功。修改前后对比如下:

connection.setRequestProperty("SOAPAction", "actionName"); connection.setRequestProperty("SOAPAction", "http://tempuri.org/actionName");

 

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。