简体   繁体   English

android java使用vb.net wcf服务

[英]android java to consume vb.net wcf service

How do I get android java to consume a vb.net wcf service, 如何让android java使用vb.net wcf服务,

this is how it looks in a VB.net Console app to connect to a wcf service. 这是它在VB.net控制台应用程序中查看连接到wcf服务的方式。 How do I write this in JAVA? 我如何在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 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

This is not working code but it gives you basic idea how you call service from android. 这不是工作代码,但它给你基本的想法如何从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());

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. 我不是最好的java程序员,但作为一个概念证明,我能够写这个并连接到我的WCF BasicHttpBinding Web服务(url是Localhost:8085 / SyncService / Connect)并上传和下载我的web包服务提供。 It's a SOAP service with a DataContract containing class that has only two parameters: a string field and a byte field. 它是一个带有DataContract的SOAP服务,该类只包含两个参数:字符串字段和字节字段。 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. 用于上传和下载二进制文件以及字符串字段的字节字段我将停止包含所有设置的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;
    }
}

This is probably overkill on the information, but maybe you can pick the parts of this that will work for you. 这可能对信息有些过分,但也许您可以选择适合您的部分内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM