如何使用HttpClient/HttpURLConnection

问题描述:

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

+0

分享一些代码和错误 – Adil

消费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

+0

我发现这个链接很有用。我有一个疑问。我的Web服务的URL是“http://116.12.173.121/brcfms/HelloWorldWebService.asmx”。它有不止一个功能。我如何通过发送函数名称和参数来调用特定函数? – mithu

+0

好的。你可以显示你正在尝试的一些代码吗? – Adil

+0

我只是关注你发送的链接。在这里,我如何发送参数并在Web服务中调用特定的方法? – mithu

我只是把Web服务的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 */