【问题标题】:Call Get WebService in Android Project在 Android 项目中调用 Get WebService
【发布时间】:2018-02-05 17:32:15
【问题描述】:

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

我的网络服务:

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

我知道 Authenticate 最好使用 POST 来确保安全,但我想测试和教育;)

谢谢

【问题讨论】:

    标签: android rest web-services wcf get


    【解决方案1】:

    试试这个函数调用网络服务

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

    【讨论】:

    • 谢谢,但我的请求方法是“GET”,你使用“POST”。
    • 用 GET 替换 POST
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-22
    • 2013-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多