Question

My web service code is following i am using WCF Restful webservices,

 [OperationContract]
    [WebInvoke(Method = "POST",
      ResponseFormat = WebMessageFormat.Json,
      BodyStyle = WebMessageBodyStyle.Wrapped,
      UriTemplate = "Login?parameter={parameter}")]
      string Login(string parameter);


 public string Login(string parameter)
    {



        /*
         * input :=  {"username":"kevin","password":"123demo"}
         * output:=  1=sucess,0=fail
         *
        */

        //Getting Parameters from Json  
        JObject jo = JObject.Parse(parameter);
        string username = (string)jo["username"];
        string password = (string)jo["password"];
        return ""+username;
}

my client side(Android) code is following

 JSONObject json = new JSONObject();
          try {
            json.put("username","demo");
            json.put("password","password123");

        HttpPost postMethod = new HttpPost(SERVICE_URI);
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        postMethod.setHeader("Accept", "application/json");
        postMethod.setHeader("Content-type", "application/json");

        nameValuePairs.add(new BasicNameValuePair("parameter",""+json.toString()));
        HttpClient hc = new DefaultHttpClient();
        postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = hc.execute(postMethod);
        Log.i("response", ""+response.toString());
        HttpEntity entity = response.getEntity();
        final String responseText = EntityUtils.toString(entity);

        string=responseText;
        Log.i("Output", ""+responseText);
        } 

        catch (Exception e) {
            // TODO Auto-generated catch block
        Log.i("Exception", ""+e);
        }

I am getting following output after calling Web service:

The server encountered an error processing the request. See server logs for more details.

Basically my problem is I am unable to pass value by using NameValuePair.

Était-ce utile?

La solution

Following code worked for me:

 public static String getJsonData(String webServiceName,String parameter)
{  
    try  
    {
    String urlFinal=SERVICE_URI+"/"+webServiceName+"?parameter=";
    HttpPost postMethod = new HttpPost(urlFinal.trim()+""+URLEncoder.encode(parameter,"UTF-8"));
    postMethod.setHeader("Accept", "application/json");
    postMethod.setHeader("Content-type", "application/json");

    HttpClient hc = new DefaultHttpClient();

    HttpResponse response = hc.execute(postMethod);
    Log.i("response", ""+response.toString());
    HttpEntity entity = response.getEntity();
    final String responseText = EntityUtils.toString(entity);

    string=responseText;
    Log.i("Output", ""+responseText);
      }
      catch (Exception e) {
    }

return string;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top