java 调用 .net web service 问题

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 调用 .net web service 问题相关的知识,希望对你有一定的参考价值。

服务端地址(115.236.89.174:90/aps.asmx?WSDL) 我用 jdk自带的 axis2和 apache cxf等第三方代理工具生成代理类都试过了 调用方法poll的时候 没有地方传头部信息设置Security对象 有没有懂webservice的高手帮我看下希望大神能帮我看下 ,下面是我代理生成的 用来调用的 但对象Security 没有办法设置到要请求的方法中
Security s=new Security();
APS ss = new APS();
PollResult objPollResult=new PollResult();
s.setDomainCode("CNLOGINK");
s.setUserID("17750");
s.setUserTokenID("NGQyMmYzMDYtNDRmOS00ZDNlLWFkYWUtMTA3ZDNlYzJkOGFkQVNfUExBVEZPUk1sb2dpbmtfMA");
objPollResult= ss.getAPSSoap().poll(); 求大神们教下 最好能写清楚 感谢
求各位帮忙看下 真心愿意会的加下圈圈1164260967 感谢 这个任务比较急

参考技术A import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

public class Servicesend implements Runnable
private String phone;
private String msg;
private String longnumber;

public Servicesend(String phone, String msg, String longnumber)
this.phone = phone;
this.msg = msg;
this.longnumber = longnumber;


public void run()
sendPost(
"http://115.236.89.174:90/aps.asmx",
"<soap12:Envelope xmlns:xsi="\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">"
+"<soap12:Header><Security xmlns=\"urn:nealnet:query:xsd:1\"><DomainCode>CNLOGINK</DomainCode><UserTokenID>NGQyMmYzMDYtNDRmOS00ZDNlLWFkYWUtMTA3ZDNlYzJkOGFkQVNfUExBVEZPUk1sb2dpbmtfMA
</UserTokenID><UserID>17750</UserID></Security></soap12:Header><soap12:Body>"
+"<Poll xmlns=\"urn:nealnet:query:xsd:1\"><EncryptionType>string</EncryptionType><ServiceTypeID>string</ServiceTypeID><SPsID>string</SPsID><BizQuerys>string</BizQuerys></Poll></soap12:Body></soap12:Envelope>"
);
//下方4个srting需要自己更改

/**
* javaÄ£Äâpost±íµ¥Ìá½»
*
* @param url
* @param param
* @return
*/
public boolean sendPost(String url, String param)
boolean bo = true;
StringBuffer buffer = null;
try
// System.out.println(param);
URL httpurl = new URL(url);
HttpURLConnection httpConn = (HttpURLConnection) httpurl
.openConnection();
httpConn.setRequestProperty("Content-Type", "text/xml;charset=GBK");
httpConn.setRequestProperty("SOAPAction", "\"\"");
httpConn.setRequestMethod("POST");
httpConn.setConnectTimeout(30000);
httpConn.setReadTimeout(30000);
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.setUseCaches(false);
PrintWriter out = new PrintWriter(httpConn.getOutputStream());
out.print(param);
out.flush();
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
String line;
while ((line = in.readLine()) != null)
buffer = new StringBuffer();
buffer.append(line);


in.close();
catch (Exception e)
e.printStackTrace();
bo = false;

return bo;


public static String sendSms(String postXML) throws Exception
String result="";
String urlString = "";
String soapActionString = "";
URL url = new URL(urlString);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
byte[] buf=postXML.getBytes();
httpConn.setRequestProperty("Content-Length", String.valueOf(buf.length));
httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
httpConn.setRequestProperty("soapActionString", soapActionString);
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
OutputStream out = httpConn.getOutputStream();
out.write(buf);
out.close();

byte[] datas = readInputStream(httpConn.getInputStream());
result = new String(datas);
return result;


public static File replace(String inFileName, String from, String to)
throws IOException, UnsupportedEncodingException
File inFile = new File(inFileName);
BufferedReader in = new BufferedReader(new InputStreamReader(
new FileInputStream(inFile), "utf-8"));
File outFile = new File(inFile + ".tmp");
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(outFile), "utf-8")));
String reading;
while ((reading = in.readLine()) != null)
out.println(reading.replaceAll(from, to));

out.close();
in.close();
return outFile;


public static byte[] readInputStream(InputStream inStream) throws Exception
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1)
outStream.write(buffer, 0, len);

byte[] data = outStream.toByteArray();
outStream.close();
inStream.close();
return data;


public static String sendpost(String mobile)
String xml="";
try
String param=mobile;
StringBuffer str=new StringBuffer();
str.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
str.append("<soap12:Envelope ");
str.append("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
str.append(" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"");
str.append(" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">");
str.append(" <soap12:Body> ");
str.append(" <GetUserInfo xmlns=\"http://MonthService.com/\"> ");
str.append(" <key>GZ01SH0062</key>");
str.append(" <phone>"+param+"</phone>");
str.append(" </GetUserInfo>");
str.append(" </soap12:Body>");
str.append(" </soap12:Envelope>");
// System.out.println(str);
xml=sendSms(str.toString());
catch (Exception e)
// TODO Auto-generated catch block
e.printStackTrace();

System.out.println(xml);
return xml;



public static void main(String[] args)
sendpost("18798669049");


后面的xml我没有修改,你可以改一下试试postxml过去
你可以参照下这个追问

嗯 谢谢了 这个我知道原生的直接调用评级xml字符串然后http请求 他们叫我用代理工具生成代理类直接调用那样就很多地方不用写死以及得到的结果等等不用直接反序列化成对象 现在问题就是我用第三方生成的代理类的时候不能找不到塞头部sercuity对象的信息

本回答被提问者采纳
参考技术B .java作为web service 的客户端去调用 .Net Web Service的服务端;

开发中遇到的问题及其解决办法有如下
1)java和.net 的默认namespace问题;

解决方案: java:http://tempuri.org
.net :http://tempuri.org/
区别就是符号“/”;如果不带“/”产生的结果会出错;
问题解决:统一加上“/”;

2)两者产生的SOAP文件格式不一致,有三种,Microsoft的;IBM的,通过抓包工具可以获得java产生的Soap消息

解决方案:SOAP 消息头问题,从上面抓包的信息可以看出:请求的是<soapenv:Envelope 而response的是<soap:Envelope
这是由于不同的服务商封装成的不同格式的soap ,但都是遵循SOAP,可以通用;
Microsoft的是 <soap:Envelope ,而IBM的是 <soapenv:Envelope ;
3)入参的数据类型会影响调用的正确性;
解决方案:
第二个参数的入参是long型。如果修改make1方法的String 型成 long 型,则程序异常;
AxisFault
faultCode: http://schemas.xmlsoap.org/soap/envelope/Client
faultSubcode:
faultString: System.Web.Services.Protocols.SoapException: Server was unable to read request. ---> System.InvalidOperationException: There is an error in XML document (1, 440). ---> System.FormatException: Input string was not in a correct format.
at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
at System.Number.ParseInt64(String value, NumberStyles options, NumberFormatInfo numfmt)
at System.Xml.XmlConvert.ToInt64(String s)

其实我们只需要在参数设置里面设成org.apache.axis.encoding.XMLType.XSD_LONG;
参考技术C 你看看你的防火墙关闭了没。追问

跟防火墙没关系吧 我用代理工具生成的代理类好像有问题 没有办法设置请求头部 对象Security 信息是用户信息要设置到请求的方法里面

追答

我这有几个用hesssion和xfire做的webservice的测试例子,能运行, 不知道你用的着不,

不同的.Net版本客户端软件调用Java Web Service区别

最近的系统中需要.Net开发的离线端软件通过Web Service技术和Java开发的在线系统进行数据交互。

在这个过程中碰到不少问题,写出来供大家参考。

Java这边在线系统基于easyUI,String Boot,mybatis技术,前后端完全分离的架构。

Java Web Service实现:

先来吐槽一下,其实如果使用Restful Json的方式与客户端交互,我们在线系统本身就支持,客户端也需要去处理soap版本的问题,实现起来更方便。可我说了不算。。。

1、Java端的代码很简单,引入包,加上webservice注解,写代码实现逻辑。

@WebService(targetNamespace = "http:/****/", endpointInterface = "******.TaskWebService")

@Component

public class TaskWebServiceImpl implements TaskWebService {


@Autowired

private SqlSessionTemplate session;

@Autowired

private QueryService queryService;


@Autowired

private EntityDao entityDao;


@Override

public List<TaskOrderInfo> getTaskOrders() {

TaskOrderReturn result = new TaskOrderReturn();

User user = User.getCurUser();

Org org = user.getOrg();

String orgLevel = org.getOrgLevel();

Map<String, Object> map = getMapByUser(user);

if (map.isEmpty()) {

return new ArrayList<TaskOrderInfo>();

}

               ......

         }

2、.Net 4.0客户端调用

在.Net Framework 2.0和4.0里生成的proxy代理类是不同的。

先来看4.0:

public partial class TaskWebServiceClient : System.ServiceModel.ClientBase

代理类继承自WCF服务Client对象,这个类是在.Net 3.0中引入WCF框架的时候添加进来的。

System.ServiceModel.ClientBase:提供用于创建可以调用服务的Windows通信基础(WCF)客户端对象的基本实现。

主要用于调用WCF创建的各种Binding类型的服务,当然也包括BasicHttpBinding也就是Soap 1.1。

接下来使用此代理类调用web服务。

这里碰到一个问题,Soap版本的问题,因为自动生成的代理类只支持soap1.1,可我们Java web服务是基于高版本的soap协议, 结果调研失败。

Java服务端改回1.1版。

接着继续。

又发现一个坑,本来应该从.Net Client 传送到Web Service上的参数,服务器接收不到。

使用Soap工具跟踪,发现soap消息里根本就没有。

后来发现生成的代理类中,所有的值类型字段都增加了一个变量名+ Specified命名的布尔字段。

默认这些字段是False,这种情况下,在调用web服务时,这些字段的值不会加入到soap消息里。

修改代码,设置这些字段为True。

                     para.startTime = DateTime.Parse("2018-05-01");

                    para.startTimeSpecified = true;

                    para.endTime = DateTime.Parse("2018 -07-01");

                    para.endTimeSpecified = true;

服务器端设置了在http header中加入了,access token进行访问控制。

.Net 4.0中在http header中加入token代码:

using (var wsClient = new wsClient.UpDownWebServiceClient())
              
            {
                using (OperationContextScope scope = new OperationContextScope(wsClient.InnerChannel))
                {
                    var httpRequestProperty = new HttpRequestMessageProperty();
                    httpRequestProperty.Headers["Authorization"] = accessTokenKey
                    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
                    downloadParam para = new downloadParam();
                    para.pageNum = 1;
                    para.pageNumSpecified = true;
                    para.pageSize = 10;
                    para.pageSizeSpecified = true;
                    para.startTime = DateTime.Parse("2018-05-01");
                    para.startTimeSpecified = true;
                    para.endTime = DateTime.Parse("2018 -07-01");
                    para.endTimeSpecified = true;

                    var list = wsClient.download(para);                 
                }

            }

调用成功!

可发现一个奇怪的问题,有个别的Web Service API行为很奇怪。这个API是返回一组数据列表,客户端调用正常,soap消息监控正常,服务器端执行正常,

可是返回到.net客户端的对象一直是空。而使用Java客户端调用和返回都是正常的。

经过监视soap消息,发现消息中其实已经返回了对象数据。怀疑是在soap消息反序列化成.net对象时候出了问题。可这个问题一直没找到原因。

3、使用.net2.0调用服务


在2.0中代理类从 System.Web.Services.Protocols.SoapHttpClientProtocol 类继承而来。

使用access token

重载代理类的 GetWebRequest方法,在http header中加入access token

 protected override System.Net.WebRequest GetWebRequest(Uri uri)

        {

            var request = base.GetWebRequest(uri);

            request.Headers.Add("Authorization", this.Authorization); // <----

            return request;

        }

如果需要在soap header加入内容:

从System.Web.Services.Protocols.SoapHeader类继承,定义自己的soapheader类:MySoapHeader

在代理类中增加属性:

 private MySoapHeader mySoapHeaderValueField;


        public MySoapHeader MySoapHeaderValue

        {

            get

            {

                return this.mySoapHeaderValueField;

            }

            set

            {

                this.mySoapHeaderValueField = value;

            }

        }

在 web方法上增加attribute声明:


/// <remarks/>

        [System.Web.Services.Protocols.SoapHeaderAttribute("MySoapHeaderValue")]

        [System.Web.Services.Protocols.SoapDocumentMethodAttribute("", RequestNamespace="http://****/", ResponseNamespace="http://****/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]

        [return: System.Xml.Serialization.XmlElementAttribute("return", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]

        public downloadReturn download([System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] downloadParam arg0) {

            object[] results = this.Invoke("download", new object[] {

                        arg0});

            return ((downloadReturn)(results[0]));

        }

调用成功,而且使用2.0调用web 服务并没有发现4.0版本发现的问题。

总结

说实话,本来应该是个很简单的问题,结果碰到一堆坑。建议大家使用Restful /Json方式进行服务器和客户端数据交互,尤其是在跨语言的情况行下,更方便,更简单,也不需要关心soap版本之类的东东。


以上是关于java 调用 .net web service 问题的主要内容,如果未能解决你的问题,请参考以下文章

怎样在java 中调用web service 传入参数返回xml?

.NET下面的web service开发,如何读取SOAP头里面的信息?

asp.net ajax客户端框架如何调用Web Service

ASP.NET4.0中JavaScript脚本调用Web Service 方法

求救Java怎么调用 net的webService

怎样用 java 调用SAP WEB SERVICE