在android中调用WCF Rest服务

时间:2013-11-16 12:32:07

标签: android wcf

我是android新手,我正在开发一个项目,其中需要通过android调用wcfrest服务或wcf服务。我的wcf服务是用于注册的,它有15个参数,我的web.config文件如下所示: -

<?xml version="1.0"?>
 <configuration>
      <configSections>
        <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
          <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
            <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
            <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
              <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere" />
              <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
              <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
              <section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
            </sectionGroup>
          </sectionGroup>
        </sectionGroup>
      </configSections>
  <connectionStrings/>
  <appSettings>
    <add key="connectionString5" value="server=ADMIN-PC\SQLEXPRESS;database=Example; integrated security=true;"/>
  </appSettings>
   <system.web>
    <!-- 
        Visual Basic options:
        Set strict="true" to disallow all data type conversions 
        where data loss can occur. 
        Set explicit="true" to force declaration of all variables.
    -->
    <compilation debug="true" strict="false" explicit="true">
      <assemblies>
        <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
      </assemblies>
    </compilation>
    <pages>
      <namespaces>
        <clear />
        <add namespace="System" />
        <add namespace="System.Collections" />
        <add namespace="System.Collections.Generic" />
        <add namespace="System.Collections.Specialized" />
        <add namespace="System.Configuration" />
        <add namespace="System.Runtime.Serialization" />
        <add namespace="System.Text" />
        <add namespace="System.Text.RegularExpressions" />
        <add namespace="System.Linq" />
        <add namespace="System.Xml.Linq" />
        <add namespace="System.ServiceModel.Web" />
        <add namespace="System.Web" />
        <add namespace="System.Web.Caching" />
        <add namespace="System.Web.SessionState" />
        <add namespace="System.Web.Security" />
        <add namespace="System.Web.Profile" />
        <add namespace="System.Web.UI" />
        <add namespace="System.Web.UI.WebControls" />
        <add namespace="System.Web.UI.WebControls.WebParts" />
        <add namespace="System.Web.UI.HtmlControls" />
      </namespaces>
      <controls>
        <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      </controls>
    </pages>
    <!--
        The <authentication> section enables configuration 
        of the security authentication mode used by 
        ASP.NET to identify an incoming user. 
    -->
    <authentication mode="Windows" />
    <!--
        The <customErrors> section enables configuration 
        of what to do if/when an unhandled error occurs 
        during the execution of a request. Specifically, 
        it enables developers to configure html error pages 
        to be displayed in place of a error stack trace.

        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
         <error statusCode="403" redirect="NoAccess.htm" />
         <error statusCode="404" redirect="FileNotFound.htm" />
        </customErrors>
    -->
    <httpHandlers>
      <remove verb="*" path="*.asmx"/>
      <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
    </httpHandlers>
    <httpModules>
      <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    </httpModules>
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" warningLevel="4"
                type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
        <providerOption name="CompilerVersion" value="v3.5"/>
        <providerOption name="OptionInfer" value="true"/>
        <providerOption name="WarnAsError" value="false"/>
      </compiler>
    </compilers>
  </system.codedom>
  <!-- 
      The system.webServer section is required for running ASP.NET AJAX under Internet
      Information Services 7.0.  It is not necessary for previous version of IIS.
  -->
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules>
      <remove name="ScriptModule" />
      <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    </modules>
    <handlers>
      <remove name="WebServiceHandlerFactory-Integrated"/>
      <remove name="ScriptHandlerFactory" />
      <remove name="ScriptHandlerFactoryAppServices" />
      <remove name="ScriptResource" />
      <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode"
           type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode"
           type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    </handlers>
  </system.webServer>
  <runtime>
    <assemblyBinding appliesTo="v2.0.05727" xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.serviceModel>
    <services>
      <service name="REST_TEST.Service1" behaviorConfiguration="REST_TEST.Service1Behavior">
        <!-- Service Endpoints -->
        <endpoint address="" binding="wsHttpBinding" contract="REST_TEST.IService1">
          <!--
              Upon deployment, the following identity element should be removed or replaced to reflect the 
              identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity 
              automatically.
          -->
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="REST_TEST.Service1Behavior">
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above 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>
  </system.serviceModel>
</configuration>
    And my java file is:-

    import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {




    EditText textfnm;
    EditText textlnm;
    EditText textmail;
    EditText textpass;
    EditText textphoned;
    EditText textphonen;
    EditText textmno;
    EditText textadl1;
    EditText textadl2;
    EditText textadl3;
    EditText textcity;
    EditText textstate;
    EditText textpocode;
    EditText textdob;
    EditText textcountry;
    TextView txtshow;
    Button btnok;
    int len;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnok=(Button)findViewById(R.id.btnok);
        //txtshow=(TextView)findViewById(R.id.textView4);
        textfnm=(EditText)findViewById(R.id.editFname);
        textlnm=(EditText)findViewById(R.id.editLname);
        textmail=(EditText)findViewById(R.id.editEmail);
        textpass=(EditText)findViewById(R.id.editPassword);
        textphoned=(EditText)findViewById(R.id.editPnumber);
        textphonen=(EditText)findViewById(R.id.editAPnumber);
        textmno=(EditText)findViewById(R.id.editMnumber);
        textadl1=(EditText)findViewById(R.id.editAddressL1);
        textadl2=(EditText)findViewById(R.id.editAddressL2);
        textadl3=(EditText)findViewById(R.id.editAddressL3);
        textcity=(EditText)findViewById(R.id.editCity1);
        textstate=(EditText)findViewById(R.id.editCounty1);
        textpocode=(EditText)findViewById(R.id.editPcode1);
        textdob=(EditText)findViewById(R.id.editDOB);
        textcountry=(EditText)findViewById(R.id.editCountry1);
        txtshow=(TextView)findViewById(R.id.textView24);
        //textshow=(EditText)findViewById(R.id.editFname);
         btnok.setOnClickListener(new View.OnClickListener() 
            {
                @Override
                public void onClick(View v) 
                {
                    String cFirstName=textfnm.getText().toString();
                    String cLastName=textlnm.getText().toString();
                    String cEmail=textmail.getText().toString();
                    String cPasword=textpass.getText().toString();
                    String cPhoneDay=textphoned.getText().toString();
                    String cPhoneNight=textphonen.getText().toString();
                    String cMobileno=textmno.getText().toString();
                    String cAdd_line_1=textadl1.getText().toString();
                    String cAdd_line_2=textadl2.getText().toString();
                    String cAdd_line_3=textadl3.getText().toString();
                    String cCIty=textcity.getText().toString();
                    String cState=textstate.getText().toString();
                    String cPostcode=textpocode.getText().toString();
                    String dDob=textdob.getText().toString();
                    String cCountry=textcountry.getText().toString();
                    //PropertyInfo pi=new PropertyInfo();
                    //pi.setName("User");
                    //pi.setValue(textunm.getText().toString());
                    //pi.setType(String.class);
                    //pi.setName("Password");
                    //pi.setValue(textpass.getText().toString());
                    //pi.setType(String.class);
                    //Use this to add parameters
                    //request.addProperty(pi);
//request.addProperty("Password",textpass.getText().toString());
                       CallSoap cs=new CallSoap();

                    try {

                        //this is the actual part that will call the webservice

                        // Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
                        // Get the SoapResult from the envelope body.
                        //SoapObject result = (SoapObject)envelope.bodyIn;
                        // SoapObject result = (SoapObject)envelope.bodyIn;

                        //String result=cs.call(username, pass);

                        String result=cs.call(cFirstName,cLastName,cEmail,cPasword,cPhoneDay,cPhoneNight,cMobileno,cAdd_line_1,cAdd_line_2,cAdd_line_3,cCIty,cState,cPostcode,dDob,cCountry);
                        //result= result.substring(44,result.length()-5);
                        Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();

                        txtshow.setText(result);

                            //txtshow.setText(result);

                        /*if(result.equals(textunm.getText().toString()))
                        {
                            //Get the first property and change the label text
                            Toast.makeText(getApplicationContext(), "Acceptable",Toast.LENGTH_LONG).show();
                        }
                        else
                        {
                            Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
                        }*/
                        /*if(result==1)
                        {
                            //Get the first property and change the label text
                            Toast.makeText(getApplicationContext(), "Acceptable",Toast.LENGTH_LONG).show();
                        }
                        else
                        {
                            Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
                        }*/
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                              }
                });
    }
    @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;
    }
}

And:-

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class CallSoap {
    public String call(String cFirstName,String cLastName,String cEmail,String cPasword,String cPhoneDay,String cPhoneNight,String cMobileno,String cAdd_line_1,String cAdd_line_2,String cAdd_line_3,String cCIty,String cState,String cPostcode,String dDob,String cCountry)
    {
        String res=null;
        try {
            DefaultHttpClient httpClient=new DefaultHttpClient();
            HttpGet httpGet=new HttpGet(" http://localhost:1806/Service1.svc/registration?cFirstName="+cFirstName+"&cLastName="+cLastName+"&cEmail="+cEmail+"&cPasword="+cPasword+"&cPhoneDay="+cPhoneDay+"&cPhoneNight="+cPhoneNight+"&cMobileno="+cMobileno+"&cAdd_line_1="+cAdd_line_1+"&cAdd_line_2="+cAdd_line_2+"&cAdd_line_3="+cAdd_line_3+"&cCity="+cCIty+"&cState="+cState+"&cPostcode="+cPostcode+"&dDob="+dDob+"&cCountry="+cCountry);           
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            InputStream stream=httpEntity.getContent();
                 //Convert the stream to readable format
            String result= convertStreamToString(stream);
            res= result;
        }
        catch(Exception e)
        {
            return e.to``String();
        }
            return res;
}
    public static String convertStreamToString(InputStream is)
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}



  By the time of calling through android i have get error "java.lang.Illegal character in scheme at index 0"

 Please help me.........

0 个答案:

没有答案