Search code examples
androidjsonweb-servicesasmxwebmethod

How to get response from .net webservice (JSON response) method to android application


I already created Webservice in asp.net which give me JSON output but when I call that webservice from android device, it give me error. I tried below code but I getting error.

LoginActivity.java

    public class LoginActivity extends Activity {

    String response;

    ProgressDialog progressDialog;
    List<NameValuePair> parameters;

    String mUrlWebServiceLogin = "http://www.example.com/MobileWeb/WS_Login.asmx/Login";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        parameters = new ArrayList<NameValuePair>();

        parameters.add(new BasicNameValuePair("userName", "xyz"));
        parameters.add(new BasicNameValuePair("password", "abc123"));

        // Call Web Service
        new CallWebService().execute();      
    }

    public class CallWebService extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            // Call Webservice for Get Menus
            WebServiceCall webServiceCall = new WebServiceCall(); // Custom class for call webservice
            response = webServiceCall.makeServiceCall(mUrlWebServiceLogin, parameters);

            Log.d("ResponseLogin:", response);

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            if (progressDialog.isShowing())
                progressDialog.dismiss();

            Toast.makeText(getApplicationContext(), "Done", Toast.LENGTH_LONG).show();
        }

        @Override
        protected void onPreExecute() {
            progressDialog = new ProgressDialog(LoginActivity.this);
            progressDialog.setMessage("Loading...");
            progressDialog.show();
            progressDialog.setCanceledOnTouchOutside(false);
            super.onPreExecute();
        }
    }
}

WebServiceCall.java

    public class WebServiceCall {

    static String response = null;
    public final static int POST = 2;

    public WebServiceCall() {
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
    }

    /*
     * Making service call
     * @url - url to make request
     * @method - http request method
     * */
    public String makeServiceCall(String url) {
        return this.makeServiceCall(url, null);
    }

    /*
     * Making service call
     * @url - url to make request
     * @method - http request method
     * @params - http request params
     * */
    public String makeServiceCall(String url, List<NameValuePair> params) {
        try {

            // http client
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;

            // Checking http request method type
            HttpPost httpPost = new HttpPost(url);

            // adding post params
            if (params != null) {
                httpPost.setEntity(new UrlEncodedFormEntity(params));
            }

            httpResponse = httpClient.execute(httpPost);

            httpEntity = httpResponse.getEntity();
            response = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return response;
    }
}

WS_Login.asmx.cs (.net webservice file)

namespace ForeverPayroll.MobileWeb
{
    /// <summary>
    /// Summary description for WS_Login
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]

    public class WS_Login : System.Web.Services.WebService
    {
        [WebMethod]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public void Login(string userName, string password)
        {
            DAL.dbOperation dboperation = new DAL.dbOperation();
            dboperation.AddParameter("@EUserID", userName);
            dboperation.AddParameter("@CompID", Convert.ToString(balUserlogin.m_Ds.Tables[0].Rows[0]["CompanyID"]));
            DataSet ds = dboperation.getDataSet("Mobile_sp_tbl_Employee_Select_Fullinfo");
            if (ds.Tables[0].Rows.Count > 0)
            {
                string[] selectedColumns = new[] { "EmployeePhoto", "EmployeeID", "EmpName", "EmployeementDate", "EDateOfBirth", "StateName", "BranchName", "CategoryName", "SubCatName", "DepartmentName", "DesignationName", "PaycaderName", "EProbation", "ECompanyEmail" };
                DataTable dt = new DataView(ds.Tables[0]).ToTable(false, selectedColumns);

                var list = new List<Dictionary<string, object>>();

                foreach (DataRow row in dt.Rows)
                {

                    var dict = new Dictionary<string, object>();

                    foreach (DataColumn col in dt.Columns)
                    {



                        row[col] = row[col].ToString();
                        dict[col.ColumnName] = row[col];
                    }
                    list.Add(dict);
                }
                HttpContext.Current.Response.Write(new JavaScriptSerializer().Serialize(list));
            }
        }
    }
}

Error (Getting below response When call webservice from android)

<html>
    <head>
    <title>Request format is unrecognized for URL unexpectedly ending in '/Login'.</title>
    <style>
    body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}
    p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
    b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
    H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
    H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
    pre {font-family:"Lucida Console";font-size: .9em}
    .marker {font-weight: bold; color: black;text-decoration: none;}
    .version {color: gray;}
    .error {margin-bottom: 10px;}
    .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
    </style>
    </head>
    <body bgcolor="white">
    <span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>
    <h2> <i>Request format is unrecognized for URL unexpectedly ending in '/Login'.</i> </h2></span>
    <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">
    <b> Description: </b>An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
    <br><br>
    <b> Exception Details: </b>System.InvalidOperationException: Request format is unrecognized for URL unexpectedly ending in '/Login'.<br><br>
    <b>Source Error:</b> <br><br>
    <table width=100% bgcolor="#ffffcc">
    <tr>
    <td>
    <code>
    An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code>
    </td>
    </tr>
    </table>
    <br>
    <b>Stack Trace:</b> <br><br>
    <table width=100% bgcolor="#ffffcc">
    <tr>
    <td>
    <code><pre>
    [InvalidOperationException: Request format is unrecognized for URL unexpectedly ending in '/Login'.]
    System.Web.Services.Protocols.WebServiceHandlerFactory.CoreGetHandler(Type type, HttpContext context, HttpRequest request, HttpResponse response) +401372
    System.Web.Services.Protocols.WebServiceHandlerFactory.GetHandler(HttpContext context, String verb, String url, String filePath) +281
    System.Web.Script.Services.ScriptHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated) +89
    System.Web.MaterializeHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +425
    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +263
    </pre></code>
    </td>
    </tr>
    </table>
    <br>
    <hr width=100% size=1 color=silver>
    <b>Version Information:</b>&nbsp;Microsoft .NET Framework Version:2.0.50727.5485; ASP.NET Version:2.0.50727.5491
    </font>
    </body>
    </html>
    <!--
    [InvalidOperationException]: Request format is unrecognized for URL unexpectedly ending in '/Login'.
            at System.Web.Services.Protocols.WebServiceHandlerFactory.CoreGetHandler(Type type, HttpContext context, HttpRequest request, HttpResponse response)
            at System.Web.Services.Protocols.WebServiceHandlerFactory.GetHandler(HttpContext context, String verb, String url, String filePath)
            at System.Web.Script.Services.ScriptHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated)
            at System.Web.HttpApplication.MaterializeHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
            at System.Web.HttpApplication.ExecuteS

When I run webservice from Visual studio 2012 at that time it will respond complete.. in JSON... Response is Below..:

[{"EmployeePhoto":"1003-defaultmale.png","EmployeeID":"1003","EmpName":"John Cena","EmployeementDate":"01 Oct 1994","EDateOfBirth":"21 Oct 1963","StateName":"Gujarat","BranchName":"Personnel and Admin","CategoryName":"Staff","SubCatName":"Technical","DepartmentName":"General Administration","DesignationName":"SENIOR CASHIER","PaycaderName":"E1","EProbation":"0","ECompanyEmail":"[email protected]"}]

Solution

  • Add into config file (after all I got the solution)

    <location path="YourWebservice.asmx">
      <system.web>
        <webServices>
          <protocols>
            <add name="HttpGet"/>
            <add name="HttpPost"/>
          </protocols>
        </webServices>
      </system.web>
    </location>