android如何利用基于Http 协议的WebService服务来获取远程数据库数据
16lz
2021-01-25
初学android,这个问题困扰了多天,在搜索引擎及论坛各位高手的帮助下,现在终于给搞定了,在这里分享给大家,希望对大家有所帮助!(其实本来是尝试用SOAP协议的,试了n天,无果,无奈又只能回到http了!)先来看看服务器端吧!
首先新建一个ASP.NET Web服务应用程序,我这里将其命名为ShopService,具体代码如下:
C#代码
然后再来看看android客户端,我就直接上代码了
Java代码
运行时记得关闭防火墙或者添加例外端口~
首先新建一个ASP.NET Web服务应用程序,我这里将其命名为ShopService,具体代码如下:
C#代码
- usingSystem;
- usingSystem.Collections;
- usingSystem.ComponentModel;
- usingSystem.Data;
- usingSystem.Linq;
- usingSystem.Web;
- usingSystem.Web.Services;
- usingSystem.Web.Services.Protocols;
- usingSystem.Xml.Linq;
- usingBLL.Shop;
- usingSystem.Web.Script.Services;
- namespaceWebService
- {
- ///<summary>
- ///ShopService的摘要说明
- ///</summary>
- [WebService(Namespace="http://具体的根据你的需要咯/")]
- [WebServiceBinding(ConformsTo=WsiProfiles.BasicProfile1_1)]
- [ToolboxItem(false)]
- //若要允许使用ASP.NETAJAX从脚本中调用此Web服务,请取消对下行的注释。
- [System.Web.Script.Services.ScriptService]
- publicclassShopService:System.Web.Services.WebService
- {
- [WebMethod]
- //[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
- publicstringgetShopItems(stringuserId,inttype)
- {
- Shopshop=newShop();
- returnshop.getShopItems(userId,type);
- }
- }
- }
然后再来看看android客户端,我就直接上代码了
Java代码
- packagecom.xxx;
- importjava.io.BufferedReader;
- importjava.io.InputStream;
- importjava.io.InputStreamReader;
- importjava.net.HttpURLConnection;
- importjava.net.URL;
- importorg.apache.http.HttpEntity;
- importorg.apache.http.HttpResponse;
- importorg.apache.http.client.methods.HttpPost;
- importorg.apache.http.entity.StringEntity;
- importorg.apache.http.impl.client.DefaultHttpClient;
- importorg.apache.http.params.BasicHttpParams;
- importorg.apache.http.params.HttpConnectionParams;
- importorg.apache.http.params.HttpParams;
- importorg.json.JSONObject;
- importandroid.graphics.Bitmap;
- importandroid.graphics.BitmapFactory;
- publicclassWebserviceTookit{
- //privatestaticfinalStringTAG="ShopItems";
- privatestaticfinalStringWEBSERVICE_IP="http://10.0.2.2:14294";
- publicstaticStringgetShopItems(StringuserId,inttype){
- try{
- //调用带参数的WebMethod
- finalStringSERVER_URL=WEBSERVICE_IP
- +"/ShopService.asmx/getShopItems";//带参数的WebMethod
- HttpPostrequest=newHttpPost(SERVER_URL);//根据内容来源地址创建一个Http请求
- request.addHeader("Content-Type","application/json;charset=utf-8");//必须要添加该Http头才能调用WebMethod时返回JSON数据
- JSONObjectjsonParams=newJSONObject();
- jsonParams.put("userId",userId);//传参
- jsonParams.put("type",type);
- HttpEntitybodyEntity=newStringEntity(jsonParams.toString(),
- "utf8");//参数必须也得是JSON数据格式的字符串才能传递到服务器端,否则会出现"{'Message':'xxx是无效的JSON基元'}"的错误
- request.setEntity(bodyEntity);
- HttpParamshttpParameters=newBasicHttpParams();
- //Setthetimeoutinmillisecondsuntilaconnectionis
- //established.
- //Thedefaultvalueiszero,thatmeansthetimeoutisnotused.
- inttimeoutConnection=3*1000;
- HttpConnectionParams.setConnectionTimeout(httpParameters,
- timeoutConnection);
- //Setthedefaultsockettimeout(SO_TIMEOUT)
- //inmillisecondswhichisthetimeoutforwaitingfordata.
- inttimeoutSocket=5*1000;
- HttpConnectionParams.setSoTimeout(httpParameters,timeoutSocket);
- DefaultHttpClienthttpClient=newDefaultHttpClient(httpParameters);
- HttpResponsehttpResponse=httpClient.execute(request);//发送请求并获取反馈
- //解析返回的内容
- if(httpResponse.getStatusLine().getStatusCode()==200)//StatusCode为200表示与服务端连接成功
- {
- StringBuilderbuilder=newStringBuilder();
- BufferedReaderbufferedReader2=newBufferedReader(
- newInputStreamReader(httpResponse.getEntity()
- .getContent()));
- for(Strings=bufferedReader2.readLine();s!=null;s=bufferedReader2.readLine()){
- builder.append(s);
- }
- StringresultString=builder.toString();
- resultString=JSONToolkit.removeEscape(resultString);
- returnresultString;
- }
- }catch(Exceptione){
- e.printStackTrace();
- return"";
- }
- return"";
- }
- }
运行时记得关闭防火墙或者添加例外端口~
更多相关文章
- 没有一行代码,「2020 新冠肺炎记忆」这个项目却登上了 GitHub 中
- Android(安卓)NDK 中使用C++源文件和使用C文件的不同
- 如何将uboot里面的参数传给recovery或kernel
- 重磅来袭!2020 年需要关注的 5 大 Android(安卓)开发技术,抓破脑袋
- Android的Linux“心”
- Android(安卓)自动点击
- Android(安卓)Studio JNI学习之(3)-使用SWIG自动生成Jni代码
- Android学习之路——简易版微信为例(二)
- android中的数据存取-方式一:preference(配置)