javaweb如何调用webservice接口,java如何调用webservice
今天小编为大家分享Windows系统下载、Windows系统教程、windows相关应用程序的文章,希望能够帮助到大家!
importjava.io.InputStreamReader;
importjava.io.UnsupportedEncodingException;
importorg.apache.http.HttpHost;
importorg.apache.http.HttpResponse;
importorg.apache.http.HttpStatus;
importorg.apache.http.HttpVersion;
importorg.apache.http.ParseException;
importorg.apache.http.client.ClientProtocolException;
importorg.apache.http.client.HttpClient;
importorg.apache.http.client.entity.UrlEncodedFormEntity;
importorg.apache.http.client.methods.HttpGet;
importorg.apache.http.client.methods.HttpPost;
importorg.apache.http.client.params.CookiePolicy;
importorg.apache.http.client.params.HttpClientParams;
importorg.apache.http.conn.params.ConnRoutePNames;
importorg.apache.http.impl.client.DefaultHttpClient;
importorg.apache.http.message.BasicNameValuePair;
importorg.apache.http.params.BasicHttpParams;
importorg.apache.http.params.HttpConnectionParams;
importorg.apache.http.params.HttpParams;
importorg.apache.http.params.HttpProtocolParams;
importorg.apache.http.protocol.HTTP;
privatestaticfinalStringUTF_8="UTF-8";
privatestaticfinalStringTAG="HttpClients";
privatestaticStringproxyHost="";
privatestaticintproxyPort=80;
privatestaticbooleanuseProxy=false;
privatestaticfinalintTIMEOUT_CONNECTION=60000;
privatestaticfinalintTIMEOUT_SOCKET=60000;
privatestaticfinalintRETRY_TIME=3;
publicStringdoHtmlPost(HttpClienthttpClient,HttpPosthttpPost)
HttpResponsehttpResponse=httpClient.execute(httpPost);
HeaderlastHeader=httpResponse.getLastHeader("Set-Cookie");
httpPost.setHeader("cookie",lastHeader.getValue());
statusCode=httpResponse.getStatusLine().getStatusCode();
if(statusCode!=HttpStatus.SC_OK){
System.out.println("HTTP"+""+"HttpMethodfailed:"+httpResponse.getStatusLine());
InputStreamis=httpResponse.getEntity().getContent();
responseBody=getStreamAsString(is,HTTP.UTF_8);
//httpClient.getConnectionManager().shutdown();
publicstaticStringdoPost(Stringurl,StringrequestData)throwsException{
//设置HTTPPOST请求参数必须用NameValuePair对象
List<BasicNameValuePair>params=newArrayList<BasicNameValuePair>();
params.add(newBasicNameValuePair("param",requestData));
UrlEncodedFormEntityentity=newUrlEncodedFormEntity(params,HTTP.UTF_8);
HttpResponsehttpResponse=httpClient.execute(httpPost);
statusCode=httpResponse.getStatusLine().getStatusCode();
if(statusCode!=HttpStatus.SC_OK){
System.out.println("HTTP"+""+"HttpMethodfailed:"+httpResponse.getStatusLine());
InputStreamis=httpResponse.getEntity().getContent();
responseBody=getStreamAsString(is,HTTP.UTF_8);
}catch(UnsupportedEncodingExceptione){
}catch(InterruptedExceptione1){
//发生致命的异常,可能是协议不对或者返回的内容有问题
}catch(ClientProtocolExceptione){
}catch(InterruptedExceptione1){
//发生致命的异常,可能是协议不对或者返回的内容有问题
}catch(InterruptedExceptione1){
}catch(InterruptedExceptione1){
httpClient.getConnectionManager().shutdown();
privatestaticStringgetStreamAsString(InputStreamstream,Stringcharset)throwsIOException{
BufferedReaderreader=newBufferedReader(newInputStreamReader(stream,charset),8192);
StringWriterwriter=newStringWriter();
while((count=reader.read(chars))>0){
publicHttpClientgetHttpClient1(){
finalHttpParamshttpParams=newBasicHttpParams();
HttpHostproxy=newHttpHost(proxyHost,proxyPort,"http");
httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
HttpConnectionParams.setConnectionTimeout(httpParams,TIMEOUT_CONNECTION);
HttpConnectionParams.setSoTimeout(httpParams,TIMEOUT_SOCKET);
HttpClientParams.setRedirecting(httpParams,true);
finalStringuserAgent="Mozilla/5.0(Windows;U;WindowsNT6.1;zh-CN;rv:1.9.2.14)Gecko/20110218Firefox/3.6.14";
HttpProtocolParams.setUserAgent(httpParams,userAgent);
HttpProtocolParams.setVersion(httpParams,HttpVersion.HTTP_1_1);
HttpClientParams.setCookiePolicy(httpParams,CookiePolicy.RFC_2109);
HttpProtocolParams.setUseExpectContinue(httpParams,false);
HttpClientclient=newDefaultHttpClient(httpParams);
privatestaticHttpClientgetHttpClient(){
finalHttpParamshttpParams=newBasicHttpParams();
HttpHostproxy=newHttpHost(proxyHost,proxyPort,"http");
httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
HttpConnectionParams.setConnectionTimeout(httpParams,TIMEOUT_CONNECTION);
HttpConnectionParams.setSoTimeout(httpParams,TIMEOUT_SOCKET);
HttpClientParams.setRedirecting(httpParams,true);
finalStringuserAgent="Mozilla/5.0(Windows;U;WindowsNT6.1;zh-CN;rv:1.9.2.14)Gecko/20110218Firefox/3.6.14";
HttpProtocolParams.setUserAgent(httpParams,userAgent);
HttpProtocolParams.setVersion(httpParams,HttpVersion.HTTP_1_1);
HttpClientParams.setCookiePolicy(httpParams,CookiePolicy.BROWSER_COMPATIBILITY);
HttpProtocolParams.setUseExpectContinue(httpParams,false);
HttpClientclient=newDefaultHttpClient(httpParams);
publicstaticvoidshowResponse(Stringstr)throwsException{
Map<String,Object>map=(Map<String,Object>)gson.fromJson(str,Object.class);
Stringvalue=(String)map.get("data");
//StringdecodeValue=Des3Request.decode(value);
//System.out.println(decodeValue);
publicstaticStringdoGet(Stringurl)throwsException{
HttpResponsehttpResponse=httpClient.execute(httpGet);
statusCode=httpResponse.getStatusLine().getStatusCode();
if(statusCode!=HttpStatus.SC_OK){
System.out.println("HTTP"+""+"HttpMethodfailed:"+httpResponse.getStatusLine());
InputStreamis=httpResponse.getEntity().getContent();
responseBody=getStreamAsString(is,HTTP.UTF_8);
}catch(UnsupportedEncodingExceptione){
}catch(InterruptedExceptione1){
//发生致命的异常,可能是协议不对或者返回的内容有问题
}catch(ClientProtocolExceptione){
}catch(InterruptedExceptione1){
//发生致命的异常,可能是协议不对或者返回的内容有问题
}catch(InterruptedExceptione1){
}catch(InterruptedExceptione1){
httpClient.getConnectionManager().shutdown();
Java调用WebService可以直接使用Apache提供的axis.jar自己编写代码,或者利用Eclipse自动生成WebService Client代码,利用其中的Proxy类进行调用。理论上是一样的,只不过用Eclipse自动生成代码省事些。
import java.rmi.RemoteException;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.message.PrefixedQName;
import org.apache.axis.message.SOAPHeaderElement;
import com.cezanne.golden.user.Exception;
import com.cezanne.golden.user.UserManagerServiceProxy;
import javax.xml.namespace.QName;
import java.net.MalformedURLException;
import javax.xml.rpc.ServiceException;
import javax.xml.soap.SOAPException;
public static String getResult() throws ServiceException, MalformedURLException, RemoteException, SOAPException
String endpoint="WebService服务地址";
Service service= new Service();
//通过Service实例创建Call的实例
Call call=(Call) service.createCall();
//将Web Service的服务路径加入到call实例之中.
call.setTargetEndpointAddress( new java.net.URL(endpoint));//为Call设置服务的位置
//由于需要认证,故需要设置调用的SOAP头信息。
Name headerName= new PrefixedQName( new QName("发布的wsdl里的targetNamespace里的url","string_itemName"));
org.apache.axis.message.SOAPHeaderElement header= new SOAPHeaderElement(headerName);
header.addTextNode("blablabla");
// SOAPHeaderElement soapHeaderElement= new SOAPHeaderElement("发布的wsdl里的targetNamespace里的url","SoapHeader");
// soapHeaderElement.setNamespaceURI("发布的wsdl里的targetNamespace里的url");
// soapHeaderElement.addChildElement("string_itemName").setValue("blablabla");
// call.addHeader(soapHeaderElement);
org.apache.axis.description.OperationDesc oper;
org.apache.axis.description.ParameterDesc param;
oper= new org.apache.axis.description.OperationDesc();
param= new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("","arg0"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("www.w3.org/2001/XMLSchema","string"), java.lang.String.class, false, false);
param= new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("","arg1"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("www.w3.org/2001/XMLSchema","string"), java.lang.String.class, false, false);
param= new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("","arg2"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("www.w3.org/2001/XMLSchema","string"), java.lang.String.class, false, false);
oper.setReturnType(new javax.xml.namespace.QName("www.w3.org/2001/XMLSchema","string"));
oper.setReturnClass(java.lang.String.class);
oper.setReturnQName(new javax.xml.namespace.QName("","return"));
oper.setStyle(org.apache.axis.constants.Style.WRAPPED);
oper.setUse(org.apache.axis.constants.Use.LITERAL);
oper.addFault(new org.apache.axis.description.FaultDesc(
new javax.xml.namespace.QName("发布的wsdl里的targetNamespace里的url","Exception"),
new javax.xml.namespace.QName("发布的wsdl里的targetNamespace里的url","Exception"),
call.setOperationName(new javax.xml.namespace.QName("发布的wsdl里的targetNamespace里的url","opName"));
String res=( String) call.invoke( new Object[]("arg0","arg1"));
System.out.println("===============");
public static void main(String[] args){
System.out.println(getResult());
} catch(MalformedURLException e){
2、利用Eclipse自动生成WebService client代码就容易多了:(由于还不会发图片,就用语言描述了,大家酬和看吧。。。)
首先,new project,选择other,在输入框中输入Web Service Client,选中搜索后的结果,点击Next,在Service definition中输入 WebService的发布地址,点击Finish
这样,WebService Client代码已经生成好了。
接下来写一个Test类,在main函数中输入如下代码:
String endpoint="服务器的WebService的地址";
YourWebServiceNameProxy umsp= new YourWebServiceNameProxy(endpoint);
String resultStr= umsp.opMethod("arg0","arg1");
System.out.println(resultStr);
System.out.println("RemoteException异常");
如果还有疑问的话还有视频,如果对你有帮助请采纳!
wwW.Xtw.Com.cN系统网专业的PC、手机系统开发下载平台,HarmonyOS系统、安卓、OS、windows电脑重装系统在线下载安装,操作系统平台技术学习,攻略教程,技术交流。
免责声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。内容仅供参考使用,不准确地方联系删除处理!
联系邮箱:773537036@qq.com