Android Studio +. Net WebService Connection __web

Source: Internet
Author: User
Tags dotnet soap serialization

The program that Android Studio connects to Visual Studio development is divided into two parts: the first part is the development of a WebService service on the Visual Studio side, and the second part is the Android The studio end invokes the service at the WebService end.

Android Studio version: Android-studio-ide-141.2178183-windows
Visual Studio version: Visual Studio WebService End Services

FILE-"New"-"website-" ASP. NET Empty Web site

Add New Item

First Choice Web Services

Renders the status shown in the following illustration. Here you can see a HelloWorld () function that returns a string "Hello World", and what we want to do in Android Studio is to display this "Hello World" string on the phone. At the same time here can also return the data in the database, displayed to the phone, you can refer to http://blog.csdn.net/zhyl8157121/article/details/8169172 this article. This article is also a reference to this article, but the platform is not the same.

When you do this, you will see the following screen in your browser:

Below I will publish this website (the content can Baidu win7 the configuration of IIS and website release etc. related knowledge). Another computer to open Visual Studio and Android Studio Two software is really a card, after the release of Visual Studio can be closed, directly in the browser access.

calling Web Service with Android Studio

The following sections refer to << crazy Android handouts >>
1. Create a new Android empty project, minimum sdk:api 15:android 4.0.3

2. Google provides a ksoap2-android project for developing Web service clients for the Android platform, but the project is not directly integrated into the Android platform and requires developers to download them themselves. For Android apps, add ksoap2-android run as follows:

1.1 Login to Http://simpligility.github.io/ksoap2-android/getting-started.html site, drop down one until the following interface. (another: Goodbye, Google Code, hello, GitHub)
  
At this point the latest is 3.5.0, and I'm downloading 3.3.0.
  
1.2 Switch to Project panel
  
Copy and paste the Ksoap2jar package directly into the App->libs directory

Right-click Add as Library ..., pop-up dialog box, OK on the line.
  
  
3. First add a button to the activity_main.xml. The code is as follows:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"
    xmlns:tools= "http:// Schemas.android.com/tools "android:layout_width=" match_parent "
    android:layout_height=" Match_parent "Android: paddingleft= "@dimen/activity_horizontal_margin"
    android:paddingright= "@dimen/activity_horizontal_margin"
    android:paddingtop= "@dimen/activity_vertical_margin"
    android:paddingbottom= "@dimen/activity_vertical_ Margin "tools:context=". Mainactivity ">


    <button
        android:layout_width=" wrap_content "
        android:layout_height=" Wrap_ Content "
        android:text=" displays "
        android:id=" @+id/btn1 "
        android:layout_alignparenttop=" true "
        Android:layout_alignparentleft= "true"
        android:layout_alignparentstart= "true"/>
</ Relativelayout>

The design interface is shown in the following illustration:

4. Mainactivity.java

Package Com.tudou.demo;
Import Android.os.Handler;
Import Android.os.Message;
Import android.support.v7.app.AppCompatActivity;
Import Android.os.Bundle;
Import Android.view.View;
Import Android.widget.Button;

Import Android.widget.Toast;
Import Org.ksoap2.SoapEnvelope;
Import Org.ksoap2.serialization.SoapObject;
Import Org.ksoap2.serialization.SoapSerializationEnvelope;
Import Org.ksoap2.transport.HttpTransportSE;

Import org.xmlpull.v1.XmlPullParserException;

Import java.io.IOException;
    public class Mainactivity extends Appcompatactivity {private Button btn1;

    Private String result; Handler Handler = new Handler () {@Override public void handlemessage (message msg) {switch (msg . What) {case 0:toast.maketext (mainactivity.this, connection Server failed, Toast.length_long). Show ()
                ;
                Case 1:toast.maketext (mainactivity.this, result, Toast.length_long). Show ();
       Default             Break
    }
        }
    };
        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);

        Setcontentview (R.layout.activity_main);


        BTN1 = (Button) Findviewbyid (R.ID.BTN1);
                Btn1.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {
            Btnclick ();
    }
        }); private void Btnclick () {final string Service_ns = "http://tempuri.org/";//namespace final string so Ap_action = "Http://tempuri.org/HelloWorld";//is used to define the address of the message request, that is, to which operation the message is sent to the final String Service_url = "http://110.240
        .192.182/webservice.asmx ";//url address, where the local address of the published Web site is written, String methodname =" HelloWorld ";
        Creates a Httptransportse transport object that is used to invoke the Web SERVICE operation final Httptransportse ht = new Httptransportse (Service_url);
        Ht.debug = true; Use the SOAP1.1 protocol to create a envelop object. From the name point of view, Soapserializationenvelope represents an SOAP message Packet, but ksoap2-android project to//soapserializationenvelope processing is more special, it is Httptransportse call Web service when the carrier of information-the client needs to pass in the parameter,
        The Bodyout property of the//soapserializationenvelope object needs to be passed to the server, and the SOAP message generated by the server response is also obtained through the object's Bodyin property.
        Final Soapserializationenvelope envelope = new Soapserializationenvelope (SOAPENVELOPE.VER11); Instantiates the Soapobject object, which needs to pass in the namespace of the Web service to be invoked, the Web service method name Soapobject Soapobject = new Soapobject (Service_ns
        , MethodName);
        Support for Dotnet WebService protocol, if dotnet webservice envelope.dotnet = true; Call the Soapserializationenvelope Setoutputsoapobject () method, or assign a value directly to the Bodyout property, and set the Soapobject object created in the first two steps to//

        Soapserializationenvelope's pay SOAP message body Envelope.bodyout = Soapobject; New Thread () {@Override public void run () {try {//Call Webservi
                    CE, invoke the call () method of the object, and invoke the remote Web Service ht.call (soap_action, envelope) with Soapserializationenvelope as a parameter; IfEnvelope.getresponse ()!= null) {//Get the SOAP message returned by the server response, after the call completes, access the Bodyin property of the Soapserializationenvelope object, the property returns a//soapobject object that represents the return message for the Web service.
                        Resolves the Soapobject object to get the return value of the calling Web service soapobject so = (soapobject) Envelope.bodyin;
                        The next step is to parse the response data from the Soapobject object in the process of result = so.getpropertyasstring (0);
                        msg = new Message ();
                        Msg.what = 1;
                    Handler.sendmessage (msg);
                        } else{message Msg=new message ();
                        msg.what=0;
                    Handler.sendmessage (msg);
                } catch (IOException e) {e.printstacktrace ();
                catch (Xmlpullparserexception e) {e.printstacktrace ();
    }}.start (); }
}

Another very important step is to add the Internet access permission to the Androidmanifest.xml file: Android.Manifest.xml

<?xml version= "1.0" encoding= "Utf-8"?> <manifest xmlns:android=
"http://schemas.android.com/apk/res/" Android "
    package=" Com.tudou.demo >
    <!--is the following sentence that allows programs to access the Internet-->
    <uses-permission android: Name= "Android.permission.INTERNET" ></uses-permission>
    <application
        android:allowbackup= " True "
        android:icon=" @mipmap/ic_launcher "
        android:label=" @string/app_name "
        android:theme=" @style/ Apptheme ">
        <activity
            android:name=". Mainactivity "
            android:label=" @string/app_name ">
            <intent-filter>
                <action android:name = "Android.intent.action.MAIN"/>
                <category android:name= "Android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>
Run. Run here to say that I am here with the real machine debugging. Open a wireless wifi in your computer before you can debug it with a real machine (360 free wifi in your notebook) desktop to buy a 360 Wi-Fi installed on the line, and then use the mobile phone to connect the WiFi, open the mobile browser to enter the address of your site to test, to see if you can access the previously published page. My name is http://255.255.255.255/WebService.asmx this address (the IP address here is the address of your website, I write here is a false address). When you can access it, connect your phone to your computer with USB, and turn on your USB debugging options.
(It is best to put the 360 mobile phone assistants on the computer out, several times the failure to connect the phone is 360 mobile phone assistant, as if to occupy a port or something). Wait a minute to see if the Android (1) Panel (2) in the lower left-hand corner shows your phone. If shown in the following illustration, the connection is displayed.

if (2) shows the red no Connected Devices, you can switch to android-sdk->platform-tools under the cmd check, the order is: ADB Devices. The following figure, if shown as shown in the following figure, proves that the phone is connected and can be run.

Configure it to start with a USB device.

In the construction of the program (the first time the words to run slightly longer, depending on the computer configuration)
The program is well installed
Click on the "Show" button on the screen to display "Hello World," the "Is my"

Here I changed the return string in the WebService.

Also here are a few questions to say:
1. It is possible that the code that accesses the network must be written to a new thread in the android2.3 version above. That's why I'm accessing the Network Code Ht.call () writes a new thread.
2. If you want to know what the SOAP protocol looks like, you can click a method name directly on the WebService page of the publishing site, and you can see the request and response information for each version of soap at the bottom of the page. Here is a list of SOAP1.1 versions.

<!--request--> post/webservice.asmx http/1.1 host:10.204.92.182 content-type:text/xml; Charset=utf-8 content-length:length soapaction: "Http://tempuri.org/HelloWorld <?xml version=" 1.0 "encoding=" Utf-8 "?> <soap:envelope xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "xmlns:xsd=" http://www.w3.org/ 2001/xmlschema "xmlns:soap=" http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body>  

OK, it's over here. ^_^

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.