如何使用HttpClient/HttpURLConnection
问题描述:
在android中调用.net webservice我已经编写了基本连接到远程数据库的.net Web服务,查询数据库并以JSON格式返回记录。我已经完成了Android中的客户端,使用ksoap2库来使用Web服务。我发现它很慢。我发现http post或http get可以用来代替这个link的SOAP。我搜索了网页,但是我找不到任何代码片段或一步一步地指导使用http post/get来调用Web服务。请使用任何代码片段或逐步指南来帮助我。如何使用HttpClient/HttpURLConnection
答
消费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));
}
答
我只是把Web服务的URL,它工作正常:)
URL u = new URL("http://www.blabla.com/Webservice.svc?anyParam=hello¶m2=Hahah");
HTTPURLConnection conn = (HTTPURLConnection) u.openConnection();
InputStream response = conn.getInputStream();
/* Do the rest */
分享一些代码和错误 – Adil