[英]android java to consume vb.net wcf service
如何讓android java使用vb.net wcf服務,
這是它在VB.net控制台應用程序中查看連接到wcf服務的方式。 我如何在JAVA中寫這個?
''http://localhost:9999/Service1.svc
Dim client As ServiceReference1.Service1Client = New ServiceReference1.Service1Client()
Dim s As String = client.GetData(2)
client.Close()
package com.example.test;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void getServiceNow(){
//this is how it looks in a VB.net Console app to connect to a wcf service
//http://localhost:9999/Service1.svc
//Dim client As ServiceReference1.Service1Client = New ServiceReference1.Service1Client()
//Dim s As String = client.GetDatas(2)
//client.Close()
}
}
wcf服務的web.config
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the value below to false before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
Public Class Service1
Implements IService1
Public Sub New()
End Sub
Public Function GetData(ByVal value As Integer) As String Implements IService1.GetData
Return String.Format("You entered: {0}", value)
End Function
Public Function GetDataUsingDataContract(ByVal composite As CompositeType) As CompositeType Implements IService1.GetDataUsingDataContract
If composite Is Nothing Then
Throw New ArgumentNullException("composite")
End If
If composite.BoolValue Then
composite.StringValue &= "Suffix"
End If
Return composite
End Function
End Class
這不是工作代碼,但它給你基本的想法如何從android調用服務。
HttpPost request = new HttpPost("http://localhost:9999/Service1.svc/GetDatas");
request.setHeader("Accept", "application/xml");
request.setHeader("Content-type", "application/xml");
StringEntity entity = new StringEntity(2);
request.setEntity(entity);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
String ss1=EntityUtils.toString(response.getEntity());
這對我有用。
我不是最好的java程序員,但作為一個概念證明,我能夠寫這個並連接到我的WCF BasicHttpBinding Web服務(url是Localhost:8085 / SyncService / Connect)並上傳和下載我的web包服務提供。 它是一個帶有DataContract的SOAP服務,該類只包含兩個參數:字符串字段和字節字段。 用於上傳和下載二進制文件以及字符串字段的字節字段我將停止包含所有設置的XML加載。
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.soap.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import sun.security.util.Debug;
public class Main {
//constants
final static String WCFNameSpace ="someurl";
final static String DataContractNameSpace ="someurl";
final static String SoapAction ="someurl";
//bare constructor
public Main(){
}
//structure for sending data back to calling program - mimics the MessageStructure from the host
public class MsgStruct{
public String _content;
public byte[] _bytes;
public MsgStruct(String s, byte[] bytes){
_content = s;
_bytes=bytes;
}
}
public MsgStruct CallHost(String URL, String Content, byte[] outBytes){
String textValue="";
byte[] inBytes =new byte[] {0};
try {
// Creating a new empty SOAP message object
SOAPMessage reqMsg = MessageFactory.newInstance().createMessage();
// Populating SOAP body
SOAPEnvelope envelope = reqMsg.getSOAPPart().getEnvelope();
SOAPBody body = envelope.getBody();
SOAPBodyElement service = body.addBodyElement(envelope.createName("HostConnect", "", WCFNameSpace)); //good here
SOAPElement paramInMsg = service.addChildElement(envelope.createName("inMsg", "", "")); //good here
SOAPElement paramBodySection = paramInMsg.addChildElement(envelope.createName("BodySection", "", DataContractNameSpace));
SOAPElement paramTextSection = paramInMsg.addChildElement(envelope.createName("TextSection", "", DataContractNameSpace));
//get the byte array to send and populate the fields
String sOut=org.apache.commons.codec.binary.Base64.encodeBase64String(outBytes);
paramBodySection.addTextNode(sOut); //adding the binary stuff here "AA=="
paramTextSection.addTextNode(Content); //adding the text content here
envelope.removeAttribute("Header");
envelope.setPrefix("s");
envelope.getBody().setPrefix("s");
// Setting SOAPAction header line
MimeHeaders headers = reqMsg.getMimeHeaders();
headers.addHeader("SOAPAction", SoapAction); //good here
headers.setHeader("Content-Type", "text/xml; charset=utf-8"); //good here
headers.setHeader("Host", "Localhost:8085"); //good here
headers.setHeader("Expect", "100-continue");
// Connecting and Calling
SOAPConnection con = SOAPConnectionFactory.newInstance().createConnection();
SOAPMessage resMsg = con.call(reqMsg, URL);
resMsg.saveChanges();
con.close();
//check the host response
if (resMsg != null){
try{
SOAPBody responseBody = resMsg.getSOAPBody();
SOAPBodyElement responseElement0= (SOAPBodyElement)responseBody.getChildElements().next();
SOAPElement responseElement1 = (SOAPElement)responseElement0.getChildElements().next();
SOAPElement bodyElement = (SOAPElement)responseElement1.getFirstChild();
SOAPElement TextElement = (SOAPElement)responseElement1.getLastChild();
Node nodeBody = (Node)bodyElement;
inBytes = getBytesFromDoc(nodeBody);
textValue = TextElement.getTextContent();
}catch (SOAPException se){
String smessage = se.getMessage();
}
return new MsgStruct(textValue,inBytes);
//no response from host
}else{
Debug.println("error","Error- nothign found");
return null;
}
} catch (Exception e) {
Debug.println("error",e.getMessage());
return null;
}
}
這可能對信息有些過分,但也許您可以選擇適合您的部分內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.