當前位置:首頁 » 網頁前端 » java調用web
擴展閱讀
webinf下怎麼引入js 2023-08-31 21:54:13
堡壘機怎麼打開web 2023-08-31 21:54:11

java調用web

發布時間: 2022-09-06 19:25:03

⑴ java程序怎麼調用webservice介面,實現發送簡訊功能

給你一個最簡單的方法:
第一、根據 拿到WSDL文件。
第二、根據Axis的jar包,把WSDL文件生成客服端java代碼。(可以把java文件打成jar文件,便於管理。怎麼生成java代碼,網路里都有說明我就不寫了。)
第三、在你工程里用AXIS的功能屬性,調用外部介面;給你一個格式模板:
MobileCodeWSLocator l=new MobileCodeWSLocator();//MobileCodeWSLocator是WSDL文件生成客服端java類;
MobileCodeWSSoap s=l.getMobileCodeWSSoap();();//MobileCodeWSSoap 是WSDL文件生成客服端java類

String m=s.getMobileCodeInfo("13811534742", "");
如果你用Axis生成的java類,格式和上面一樣;自己參考一下就懂了。

你上面明顯的連接異常,第三方服務明顯沒有開,WEBSERVICE可以設置戶名、密碼,像行所有的WEBSERVICE都設置,安全考慮吧。

⑵ java實現調用webserver

一、利用jdk web服務api實現,這里使用基於 SOAP message 的 Web 服務
1.首先建立一個Web services EndPoint:

Java代碼

package Hello;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.xml.ws.Endpoint;

@WebService
public class Hello {

@WebMethod
public String hello(String name) {
return "Hello, " + name + "\n";
}

public static void main(String[] args) {
// create and publish an endpoint
Hello hello = new Hello();
Endpoint endpoint = Endpoint.publish("http://localhost:8080/hello", hello);
}
}

Java代碼

package Hello;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.xml.ws.Endpoint;

@WebService
public class Hello {

@WebMethod
public String hello(String name) {
return "Hello, " + name + "\n";
}

public static void main(String[] args) {
// create and publish an endpoint
Hello hello = new Hello();
Endpoint endpoint = Endpoint.publish("http://localhost:8080/hello", hello);
}
}

2.使用 apt 編譯 Hello.java(例:apt -d [存放編譯後的文件目錄] Hello.java ) ,會生成 jaws目錄
3.使用java Hello.Hello運行,然後將瀏覽器指向http://localhost:8080/hello?wsdl就會出現下列顯示
4.使用wsimport 生成客戶端
使用如下:wsimport -p . -keep http://localhost:8080/hello?wsdl
5.客戶端程序:

Java代碼

class HelloClient{
public static void main(String args[]) {
HelloService service = new HelloService();
Hello helloProxy = service.getHelloPort();
String hello = helloProxy.hello("你好");
System.out.println(hello);
}
}

Java代碼

class HelloClient{
public static void main(String args[]) {
HelloService service = new HelloService();
Hello helloProxy = service.getHelloPort();
String hello = helloProxy.hello("你好");
System.out.println(hello);
}
}

⑶ java 怎樣調用.net 寫的webservice

一. 使用axis1.x調用webservice方法
Axis的最常用版本:1.4和2.0版本。以下為1.4版本
核心代碼:
// webserviceURL
service_url = "http://vip.cxcod.com/PodApi/GetPodStr.asmx?wsdl";
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress(new java.net.URL(service_url));
// 設置要調用的方法
// http://intelink.net/是wsdl中definitions根節點的targetNamespace屬性值
call.setOperationName(new QName("http://intelink.net/","GetStrByJobno"));
// 該方法需要的參數
call.addParameter("CustNo",
org.apache.axis.encoding.XMLType.XSD_STRING,
javax.xml.rpc.ParameterMode.IN);
call.addParameter("passwd",
org.apache.axis.encoding.XMLType.XSD_STRING,
javax.xml.rpc.ParameterMode.IN);
call.addParameter("Jobno",
org.apache.axis.encoding.XMLType.XSD_STRING,
javax.xml.rpc.ParameterMode.IN);
// 方法的返回值類型
call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);
// call.setUseSOAPAction(true); //call.setSOAPActionURI("http://intelink.net/GetStrByJobno");
// 調用該方法, new Object[] { CustNo, passwd, Jobno}為參數列表
String xmlStr = call.invoke(new Object[] { CustNo, passwd, Jobno}).toString();
} catch (Exception e) {
e.printStackTrace();
}
JAVA用這種方式調用webservice,需要注意的地方:
1. 伺服器未能識別 HTTP 標頭 SOAPAction 的值:
症狀一:
Web Service + ASP.NET 應用程序部署到伺服器默認目錄中,在IE中用http://<伺服器地址>/<程序目錄名>/<默認啟動頁面名>發生「伺服器未能識別 HTTP 標頭 SOAPAction 的值」錯誤。
症狀二:
在Java平台上調用.NET Web Service的服務時,出現"伺服器未能識別 HTTP 標頭 SOAPAction 的值"。
症狀三:
在Java平台下調用.NET WEB Service,出現數據時有時無。

解決對策:

給.NET的WebService類(即.asmx文件下的類)添加屬性[SoapDocumentService(RoutingStyle=SoapServiceRoutingStyle.RequestElement)]
小知識:
什麼是SoapAction?它在WSDL中有何作用?
SOAPAction HTTP request header被用來標識SOAP HTTP請求的目的地,其值是個URI地址。SOAP發送並不限制格式、URI特徵或其必須可解析,那麼在這種情況下,發送一個HTTP SOAP請求時,其HTTP客戶端必須使用/指明SOAPAction HTTP request header。

SOAPAction header的內容可以被用在服務端,諸如:防火牆適當的過濾基於HTTP的SOAP請求消息等場景。SOAPAction header的值為空串("")表示SOAP消息的目的地由HTTP請求的URI標識;無值則表示沒有指定這條消息的目的地。

本人補充:
在.NET環境調用.NET WebService出現 「SOAPAction 值在 XML Web services 的所有方法中不唯一的錯誤」,也可以通過此法解決。

2. 為了Java能夠調用WebService的方法,所以。NETP寫的WebServiced的每個方法都要聲明為Rpc方法,即添加"[SoapRpcMethod.....]".
例如:[WebMethod]
[SoapRpcMethod(Use=SoapBindingUse.Literal,Action= http://tempuri.org/HelloWorld", RequestNamespace = "http://tempuri.org/", ResponseNamespace = "http://tempuri.org/")]

3. 對返回值、參數的處理上:
應盡量將webservice方法的返回值、參數都寫成字元串(String)不要使用復雜對象類型,這樣便於在網路上傳輸。避免了復雜對象類型的不易轉換問題。。。對於返回類型是字元串數組型的,可以設置返回類型為org.apache.axis.encoding.XMLType.SOAP_VECTOR或java.lang.String[].class.

二.利用xfire調用WebService
XFire是新一代的Java Web服務引擎,XFire使得在JavaEE應用中發布Web服務變得輕而易舉。和其他Web服務引擎相比,XFire的配置非常簡單,可以非常容易地和Spring集成,它使得Java開發人員終於可以獲得和.Net開發人員一樣的開發效率。

核心代碼:
Service service = new ObjectServiceFactory().create(IWebservice.class);
XFireProxyFactory factory =
new XFireProxyFactory(XFireFactory.newInstance().getXFire());
String url= "http://localhost:8080/webservices/services/webservices";
IWebservice iw = (IWebservice) factory.create(service, url);
List list=iw.getTest();
出處:http://liyuandong.iteye.com/blog/567836

⑷ java如何調用webservice介面

Java通過WSDL文件來調用webservice直接調用模式如下:

import java.util.Date;

import java.text.DateFormat;

import org.apache.axis.client.Call;

import org.apache.axis.client.Service;

import javax.xml.namespace.QName;

import java.lang.Integer;

import javax.xml.rpc.ParameterMode;

public class caClient {

public static void main(String[] args) {

try {

String endpoint = "http://localhost:8080/ca3/services/caSynrochnized?wsdl";

//直接引用遠程的wsdl文件

//以下都是套路

Service service = new Service();

Call call = (Call) service.createCall();

call.setTargetEndpointAddress(endpoint);

call.setOperationName("addUser");//WSDL裡面描述的介面名稱

call.addParameter("userName", org.apache.axis.encoding.XMLType.XSD_DATE,

javax.xml.rpc.ParameterMode.IN);//介面的參數

call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);//設置返回類型

String temp = "測試人員";

String result = (String)call.invoke(new Object[]{temp});

//給方法傳遞參數,並且調用方法

System.out.println("result is "+result);

}

catch (Exception e) {

System.err.println(e.toString());

}

}

}

⑸ java怎麼調用webservice

1.使用HttpClient
用到的jar文件:commons-httpclient-3.1.jar
方法:
預先定義好Soap請求數據,可以藉助於XMLSpy Professional軟體來做這一步生成。

String soapRequestData = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<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:Body>" +
" <getCountryCityByIp xmlns=\"http://WebXml.com.cn/\">" +
" <theIpAddress>219.137.167.157</theIpAddress>" +
" </getCountryCityByIp>" +
" </soap12:Body>" +
"</soap12:Envelope>";

然後定義一個PostMethod,這時需要指定web服務的Url;

PostMethod postMethod = new PostMethod(「http://www.webxml.com.cn/WebServices/IpAddressSearchWebService.asmx」);

然後把Soap請求數據添加到PostMethod中

byte[] b = soapRequestData.getBytes("utf-8");
InputStream is = new ByteArrayInputStream(b,0,b.length);
RequestEntity re = new InputStreamRequestEntity(is,b.length,"application/soap+xml; charset=utf-8");
postMethod.setRequestEntity(re);

最後生成一個HttpClient對象,並發出postMethod請求

HttpClient httpClient = new HttpClient();
statusCode = httpClient.executeMethod(postMethod);
String soapRequestData = postMethod.getResponseBodyAsString();

soapRequestData就是調用web服務的Soap響應數據,是xml格式的,可以通過解析soapRequestData來獲得調用web服務的返回值。
2.使用Xfire
用到的jar文件xfire-all-1.2.4.jar, jdom-1.0.jar
方法:
定義一個Client對象,指定web服務的wsdl的地址

Client c = new Client(new URL(「http://www.webxml.com.cn/WebServices/IpAddressSearchWebService.asmx?wsdl」));

調用Client對象的invoke方法,指定web服務的方法名,和參數,返回值是一個Object型的數組。
下面代碼調用getVersionTime方法,這個方法沒有參數用所以後一個參數使用new Object[0]。

Object[] results = c.invoke(「getVersionTime」, new Object[0]);

3.使用axis2
下載axis2-1.4
方法:
打開控制台,進入axis2-1.4/bin目錄

wsdl2java.bat -uri http://www.webxml.com.cn/WebServices/IpAddressSearchWebService.asmx?wsdl -p ws.clinet.axis2

上述命令執行完後,會在當前目錄下生成一個src目錄,在src\ ws\ clinet\ axis2目錄里生成XXXXCallbackHandler.java和XXXXStub.java兩個文件。
wsdl2java 會根據wsdl文件生成web服務的調用介面,參數類,返回值的類。
在調用webservice的時候直接實例化一個XXXXStub的對象,然後調用web服務的方法就可以了。
4. 總結
針對某種工具搭建的Web Service服務可能有與其對應的更簡單的調用方法,在這里沒有做描述,上述的調用web服務的方法是通用的。
上述三種方法中使用httpclient應該是比較靈活,但是開發效率低,難度大,使用Xfire和axis2比較容易,開發速度快,但是axis2通用性不好,有的web服務用axis2不好用。httpclient和Xfire通用性比較好,鑒於以上特點推薦使用Xfire。

⑹ 怎麼用Java通過wsdl地址調用WebService求代碼

我覺得這種方法比較適合那些高手,他們能直接看懂XML格式的WSDL文件,我自己是看不懂的,尤其我不是專門搞這行的,即使一段時間看懂,後來也就忘記了。直接調用模式如下:
import java.util.Date;
import java.text.DateFormat;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import javax.xml.namespace.QName;
import java.lang.Integer;
import javax.xml.rpc.ParameterMode;

public class caClient {

public static void main(String[] args) {

try {
String endpoint = "http://localhost:8080/ca3/services/caSynrochnized?wsdl";
//直接引用遠程的wsdl文件
//以下都是套路
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress(endpoint);
call.setOperationName("addUser");//WSDL裡面描述的介面名稱
call.addParameter("userName", org.apache.axis.encoding.XMLType.XSD_DATE,
javax.xml.rpc.ParameterMode.IN);//介面的參數
call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);//設置返回類型

String temp = "測試人員";
String result = (String)call.invoke(new Object[]{temp});
//給方法傳遞參數,並且調用方法
System.out.println("result is "+result);
}
catch (Exception e) {
System.err.println(e.toString());
}
}
}
2,直接SOAP調用遠程的webservice
這種模式我從來沒有見過,也沒有試過,但是網路上有人貼出來,我也轉過來
import org.apache.soap.util.xml.*;
import org.apache.soap.*;
import org.apache.soap.rpc.*;

import java.io.*;
import java.net.*;
import java.util.Vector;

public class caService{
public static String getService(String user) {
URL url = null;
try {
url=new URL("http://192.168.0.100:8080/ca3/services/caSynrochnized");
} catch (MalformedURLException mue) {
return mue.getMessage();
}
// This is the main SOAP object
Call soapCall = new Call();
// Use SOAP encoding
soapCall.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);
// This is the remote object we're asking for the price
soapCall.setTargetObjectURI("urn:xmethods-caSynrochnized");
// This is the name of the method on the above object
soapCall.setMethodName("getUser");
// We need to send the ISBN number as an input parameter to the method
Vector soapParams = new Vector();

// name, type, value, encoding style
Parameter isbnParam = new Parameter("userName", String.class, user, null);
soapParams.addElement(isbnParam);
soapCall.setParams(soapParams);
try {
// Invoke the remote method on the object
Response soapResponse = soapCall.invoke(url,"");
// Check to see if there is an error, return "N/A"
if (soapResponse.generatedFault()) {
Fault fault = soapResponse.getFault();
String f = fault.getFaultString();
return f;
} else {
// read result
Parameter soapResult = soapResponse.getReturnValue ();
// get a string from the result
return soapResult.getValue().toString();
}
} catch (SOAPException se) {
return se.getMessage();
}
}
}

⑺ Java客戶端調用Webservice介面流程

給你看看以前寫的獲取電話號碼歸屬地的代碼的三種方法,然後你就懂了。

importjava.io.ByteArrayOutputStream;
importjava.io.FileInputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.net.HttpURLConnection;
importjava.net.URL;

importorg.apache.commons.httpclient.HttpClient;
importorg.apache.commons.httpclient.HttpException;
importorg.apache.commons.httpclient.methods.PostMethod;

publicclassMobileCodeService{

publicvoidhttpGet(Stringmobile,StringuserID)throwsException
{
//http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo?mobileCode=string&userID=string
URLurl=newURL("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo?mobileCode="+mobile+"&userID="+userID);
HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");

if(conn.getResponseCode()==HttpURLConnection.HTTP_OK)//200
{
InputStreamis=conn.getInputStream();

=newByteArrayOutputStream();//

byte[]buf=newbyte[1024];
intlen=-1;
while((len=is.read(buf))!=-1)
{
//獲取結果
arrayOutputStream.write(buf,0,len);
}

System.out.println("Get方式獲取的數據是:"+arrayOutputStream.toString());
arrayOutputStream.close();
is.close();
}
}


publicvoidhttpPost(Stringmobile,StringuserID)throwsHttpException,IOException
{
//訪問路徑http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo
//HttpClient訪問

HttpClienthttpClient=newHttpClient();
PostMethodpm=newPostMethod("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo");

pm.setParameter("mobileCode",mobile);
pm.setParameter("userID",userID);

intcode=httpClient.executeMethod(pm);
System.out.println("狀態碼:"+code);

//獲取結果
Stringresult=pm.getResponseBodyAsString();
System.out.println("獲取到的數據是:"+result);
}

publicvoidSOAP()throwsException
{
HttpClientclient=newHttpClient();

PostMethodmethod=newPostMethod("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx");

//設置訪問方法的參數
method.setRequestBody(newFileInputStream("C:\soap.xml"));

method.setRequestHeader("Content-Type","text/xml;charset=utf-8");

intcode=client.executeMethod(method);
System.out.println("狀態碼:"+code);

//獲取結果
Stringresult=method.getResponseBodyAsString();
System.out.println("獲取到的數據是:"+result);
}

publicstaticvoidmain(String[]args)throwsException{
MobileCodeServicemcs=newMobileCodeService();
mcs.httpGet("18524012513","");
//mcs.httpPost("18524012513","");
//mcs.SOAP();
}
}