android如何利用基于Http 协议的WebService服务来获取远程数据库数据

初学android,这个问题困扰了多天,在搜索引擎及论坛各位高手的帮助下,现在终于给搞定了,在这里分享给大家,希望对大家有所帮助!(其实本来是尝试用SOAP协议的,试了n天,无果,无奈又只能回到http了!)先来看看服务器端吧! 

首先新建一个ASP.NET Web服务应用程序,我这里将其命名为ShopService,具体代码如下: 
C#代码   收藏代码
  1. using System;  
  2. using System.Collections;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Linq;  
  6. using System.Web;  
  7. using System.Web.Services;  
  8. using System.Web.Services.Protocols;  
  9. using System.Xml.Linq;  
  10. using BLL.Shop;  
  11. using System.Web.Script.Services;  
  12.   
  13. namespace WebService  
  14. {  
  15.     /// <summary>  
  16.     /// ShopService 的摘要说明  
  17.     /// </summary>  
  18.     [WebService(Namespace = "http://具体的根据你的需要咯/")]  
  19.     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
  20.     [ToolboxItem(false)]  
  21.     // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。  
  22.     [System.Web.Script.Services.ScriptService]  
  23.   
  24.     public class ShopService : System.Web.Services.WebService  
  25.     {  
  26.         [WebMethod]  
  27.         //[ScriptMethod(ResponseFormat = ResponseFormat.Json)]  
  28.         public string getShopItems(string userId, int type)  
  29.         {  
  30.             Shop shop = new Shop();  
  31.             return shop.getShopItems(userId, type);  
  32.         }  
  33.     }  
  34. }  

然后再来看看android客户端,我就直接上代码了 
Java代码   收藏代码
  1. package com.xxx;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.InputStream;  
  5. import java.io.InputStreamReader;  
  6. import java.net.HttpURLConnection;  
  7. import java.net.URL;  
  8.   
  9. import org.apache.http.HttpEntity;  
  10. import org.apache.http.HttpResponse;  
  11. import org.apache.http.client.methods.HttpPost;  
  12. import org.apache.http.entity.StringEntity;  
  13. import org.apache.http.impl.client.DefaultHttpClient;  
  14. import org.apache.http.params.BasicHttpParams;  
  15. import org.apache.http.params.HttpConnectionParams;  
  16. import org.apache.http.params.HttpParams;  
  17. import org.json.JSONObject;  
  18.   
  19. import android.graphics.Bitmap;  
  20. import android.graphics.BitmapFactory;  
  21.   
  22. public class WebserviceTookit {  
  23.     // private static final String TAG = "ShopItems";  
  24.     private static final String WEBSERVICE_IP = "http://10.0.2.2:14294";  
  25.   
  26.     public static String getShopItems(String userId, int type) {  
  27.         try {  
  28.             // 调用带参数的WebMethod  
  29.             final String SERVER_URL = WEBSERVICE_IP  
  30.                     + "/ShopService.asmx/getShopItems"// 带参数的WebMethod  
  31.             HttpPost request = new HttpPost(SERVER_URL); // 根据内容来源地址创建一个Http请求  
  32.             request.addHeader("Content-Type""application/json; charset=utf-8");// 必须要添加该Http头才能调用WebMethod时返回JSON数据  
  33.             JSONObject jsonParams = new JSONObject();  
  34.             jsonParams.put("userId", userId);// 传参  
  35.             jsonParams.put("type", type);  
  36.             HttpEntity bodyEntity = new StringEntity(jsonParams.toString(),  
  37.                     "utf8");// 参数必须也得是JSON数据格式的字符串才能传递到服务器端,否则会出现"{'Message':'xxx是无效的JSON基元'}"的错误  
  38.             request.setEntity(bodyEntity);  
  39.   
  40.             HttpParams httpParameters = new BasicHttpParams();  
  41.             // Set the timeout in milliseconds until a connection is  
  42.             // established.  
  43.             // The default value is zero, that means the timeout is not used.  
  44.             int timeoutConnection = 3 * 1000;  
  45.             HttpConnectionParams.setConnectionTimeout(httpParameters,  
  46.                     timeoutConnection);  
  47.             // Set the default socket timeout (SO_TIMEOUT)  
  48.             // in milliseconds which is the timeout for waiting for data.  
  49.             int timeoutSocket = 5 * 1000;  
  50.             HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);  
  51.   
  52.             DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);  
  53.             HttpResponse httpResponse = httpClient.execute(request); // 发送请求并获取反馈  
  54.             // 解析返回的内容  
  55.             if (httpResponse.getStatusLine().getStatusCode() == 200// StatusCode为200表示与服务端连接成功  
  56.             {  
  57.                 StringBuilder builder = new StringBuilder();  
  58.                 BufferedReader bufferedReader2 = new BufferedReader(  
  59.                         new InputStreamReader(httpResponse.getEntity()  
  60.                                 .getContent()));  
  61.                 for (String s = bufferedReader2.readLine(); s != null; s = bufferedReader2.readLine()) {  
  62.                     builder.append(s);  
  63.                 }  
  64.   
  65.                 String resultString = builder.toString();  
  66.                 resultString = JSONToolkit.removeEscape(resultString);  
  67.   
  68.                 return resultString;  
  69.             }  
  70.         } catch (Exception e) {  
  71.             e.printStackTrace();  
  72.             return "";  
  73.         }  
  74.         return "";  
  75.     }  
  76. }  


运行时记得关闭防火墙或者添加例外端口~
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值