如何使用HttpClient / HttpURLConnection在android中调用.net webservice

时间:2012-08-29 06:22:16

标签: android web-services http-post httpclient

我编写了一个基本连接到远程数据库的.net Web服务,查询数据库并以JSON格式返回记录。我在Android中完成了客户端以使用kso​​ap2库来使用Web服务。我发现它很慢。我发现可以使用http post或http get代替来自link的SOAP。我在网上搜索但我找不到任何代码片段或分步指南使用http post / get来调用Web服务。请帮我处理任何代码段或分步指南。

2 个答案:

答案 0 :(得分:2)

使用JSON响应非常简单。我的一位办公室同事为初学者写了一篇关于“带有WCF服务的Android”的博客文章以及演示代码。

以下是来自源代码的代码段:

    DefaultHttpClient client = new DefaultHttpClient();

    // http get request
    HttpGet request = new HttpGet(EMPLOYEE_SERVICE_URI
            + evEmployeeId.getText());
    // set the hedear to get the data in JSON formate
    request.setHeader("Accept", "application/json");
    request.setHeader("Content-type", "application/json");
    // get the response
    HttpResponse response = client.execute(request);
    HttpEntity entity = response.getEntity();
    // if entity contect lenght 0, means no employee exist in the system
    // with these code
    if (entity.getContentLength() != 0) {
        // stream reader object
        Reader employeeReader = new InputStreamReader(response.getEntity()
                .getContent());
        // create a buffer to fill if from reader
        char[] buffer = new char[(int) response.getEntity()
                .getContentLength()];
        // fill the buffer by the help of reader
        employeeReader.read(buffer);
        // close the reader streams
        employeeReader.close();
        // for the employee json object
        JSONObject employee = new JSONObject(new String(buffer));
    }

LINK TO BLOG POST

答案 1 :(得分:-1)

我只是放了Web Service的URL,它工作正常:)

URL u = new URL("http://www.blabla.com/Webservice.svc?anyParam=hello&param2=Hahah");

HTTPURLConnection conn = (HTTPURLConnection) u.openConnection();
InputStream response = conn.getInputStream();



/* Do the rest */