2017-08-28 43 views
-1

我有一个GET webinvoke的Authenticate Rest服务。我必须通过我的服务发送用户名和密码。我必须在我的项目中使用AsyncTask调用它,但我不知道如何使用json类型将我的参数(用户名和密码)发送到服务器。我可以这样做吗?如果是,如何?在Android项目中调用获取WebService

我的web服务:

[OperationContract] 
    [WebGet(UriTemplate = "/Authenticate", 
     ResponseFormat = WebMessageFormat.Json, 
     BodyStyle = WebMessageBodyStyle.Wrapped)] 
    Test<Person> Authenticate(string user,string password) 

在我的Android项目的代码,我转换的JSONObject串,我想发送到服务器:

HttpGet request = new HttpGet("my URL"); 
response = httpClient.execute(request); 

我知道身份验证时最好使用POST为了安全,但我想测试和教育;)

谢谢

回答

0

尝试th是函数调用web服务

public static String retrieveStream(String link, String parameters) { 
    try { 
     link = link.replace(" ", "%20"); 
     // parameters = parameters.replace(" ", "%20"); 
     URL url = new URL(link); 

     HttpURLConnection connection = (HttpURLConnection) url 
       .openConnection(); 
     connection.setDoOutput(true); 
     connection.setRequestProperty("Content-Type", 
       "application/x-www-form-urlencoded"); 

     connection.setRequestMethod("POST"); 

     OutputStreamWriter request = new OutputStreamWriter(
       connection.getOutputStream()); 
     request.write(parameters); 
     request.flush(); 
     request.close(); 

     String line = ""; 
     InputStreamReader isr = new InputStreamReader(
       connection.getInputStream()); 
     BufferedReader reader = new BufferedReader(isr); 
     StringBuilder sb = new StringBuilder(); 
     while ((line = reader.readLine()) != null) { 
      sb.append(line); 
     } 
     // Response from server after login process will be stored in 
     // response variable. 
     String response = sb.toString(); 
     // You can perform UI operations here 
     isr.close(); 
     reader.close(); 
     return response; 

    } catch (IOException ignored) { 
     ignored.printStackTrace(); 
    } 
    return ""; 
} 
+0

谢谢但我的请求方法是“GET”,您使用“POST”。 – Fahim

+0

用GET替换POST –

相关问题