如何从.net webservice(JSON响应)方法得到响应android应用

如何从.net webservice(JSON响应)方法得到响应android应用

问题描述:

我已经在asp.net中创建了Webservice,它给了我JSON输出,但是当我从android设备调用webservice时,它给了我错误。 我尝试了下面的代码,但我得到错误。如何从.net webservice(JSON响应)方法得到响应android应用

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 web服务文件)

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)); 
      } 
     } 
    } 
} 

错误(以下入门响应当从Android的电话web服务)

<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 

当我在那个时候运行从Visual Studio 2012的web服务则回答完整。在JSON ...响应如下..:

[{"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]"}] 

添加到配置文件(毕竟我得到了解决)

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

似乎您的网址是错误的

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

您的网址追加到此?userName=xyz&password=abc123和请求在您的浏览器中。如果你得到JSON响应,你的android代码必须工作。

编辑 测试后要求使用卷曲

curl --data "userName=xyz&password=abc123" http://example.com 
+0

我已经尝试过,但它不工作 –

+0

我不熟悉.net,你确定你的服务网址是正确的吗?'[WebService(Namespace =“http://tempuri.org/”)]'。然后,如果你测试真正的Android设备,你的服务必须可以从本地网络访问。 – AliNadi

+0

@DanielNugent感谢您的关注。我添加了curl示例来测试发布请求。 – AliNadi