Reputation: 9545
How do I get android java to consume a vb.net wcf service,
this is how it looks in a VB.net Console app to connect to a wcf service. How do I write this in 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()
}
}
web.config of the wcf service
<?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
Upvotes: 0
Views: 590
Reputation: 3713
This worked for me.
I'm not the best java programmer around, but as a proof of concept I was able to write this and connect to my WCF BasicHttpBinding web service (url was Localhost:8085/SyncService/Connect) and upload and download the packages that my web service provices. It's a SOAP service with a DataContract containing class that has only two parameters: a string field and a byte field. The byte field I used for uploading and downloading binaries and into the string field I'd stop a butt load of XML that wrapped up all settings.
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;
}
}
This is probably overkill on the information, but maybe you can pick the parts of this that will work for you.
Upvotes: 1
Reputation: 2171
This is not working code but it gives you basic idea how you call service from 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());
Upvotes: 1