android客户端访问服务端,服务端返回json数据
生活随笔
收集整理的這篇文章主要介紹了
android客户端访问服务端,服务端返回json数据
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
json這里選用了fast-json
先看服務(wù)端代碼如下
package?novelserver.servlet;import?java.io.IOException; import?java.io.PrintWriter; import?java.util.List;import?javax.servlet.ServletException; import?javax.servlet.annotation.WebServlet; import?javax.servlet.http.HttpServlet; import?javax.servlet.http.HttpServletRequest; import?javax.servlet.http.HttpServletResponse;import?model.Novel; import?spider.BiqugeNovelPageProcesser; import?spider.BiqugeNovelPipeline; import?spider.NovelList; import?us.codecraft.webmagic.Spider;import?com.alibaba.fastjson.JSON; /***?首頁(yè)推薦*?@author?liangzhenghui**/ @WebServlet(urlPatterns={"/homeRecommend"}) public?class?HomeRecommend?extends?HttpServlet?{private?static?final?long?serialVersionUID?=?430306605309121990L;@Overrideprotected?void?doGet(HttpServletRequest?req,?HttpServletResponse?resp)throws?ServletException,?IOException?{doPost(req,?resp);}@Overrideprotected?void?doPost(HttpServletRequest?req,?HttpServletResponse?resp)throws?ServletException,?IOException?{//筆趣閣String?url?=?"http://www.biquge.com/";Spider.create(new?BiqugeNovelPageProcesser()).addUrl(url).addPipeline(new?BiqugeNovelPipeline()).run();List<Novel>?novelList?=?NovelList.getNovelList();//解決中文亂碼問(wèn)題resp.setContentType("text/html;charset=UTF-8");??//目的是為了控制瀏覽器的行為,即控制瀏覽器用UTF-8進(jìn)行解碼;//的目的是用于response.getWriter()輸出的字符流的亂碼問(wèn)題,如果是response.getOutputStream()是不需要此種解決方案的;因?yàn)檫@句話的意思是為了將response對(duì)象中的數(shù)據(jù)以UTF-8編碼后發(fā)向?yàn)g覽器;resp.setCharacterEncoding("UTF-8");?PrintWriter?out?=?resp.getWriter();out.write(JSON.toJSONString(novelList));} }android客戶端向服務(wù)端發(fā)起請(qǐng)求以及接收返回?cái)?shù)據(jù)代碼如下
public?static?List<Novel>?getHotNovelList()?{List<Novel>?novelList?=?new?ArrayList<Novel>();String?url?=?"http://192.168.1.104:8080/novel/homeRecommend";DefaultHttpClient?httpclient?=?new?DefaultHttpClient();HttpGet?httpGet?=?new?HttpGet(url);try?{HttpResponse?response?=?httpclient.execute(httpGet);novelList?=?JSON.parseArray(EntityUtils.toString(response.getEntity()),?Novel.class);}?catch?(ClientProtocolException?e)?{e.printStackTrace();}?catch?(IOException?e)?{e.printStackTrace();}return?novelList;}轉(zhuǎn)載于:https://my.oschina.net/liangzhenghui/blog/197117
總結(jié)
以上是生活随笔為你收集整理的android客户端访问服务端,服务端返回json数据的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: python导入xlsxwriter要安
- 下一篇: python3 携程_多任务(3):协程