android客户端与服务端交互的工具类
客户端:
public class HttpUtil { //创建HttpClient对象 public static HttpClient httpClient = new DefaultHttpClient(); public static final String BASE_URL="http://xxx.xxxx.xx.xx:8080/ticket/"; // public static final String BASE_URL="http://xxx.xxxx.xx.xx:8080/apk/"; // public static final String BASE_URL = "www.baidu.com"; /** * * @param url 发送请求的Url * @return 服务器响应的字符串 * @throws Exception * @throws InterruptedException */ public static String getRequest(final String url) throws Exception { FutureTask<String> task = new FutureTask<String>( new Callable<String>() { @Override public String call() throws Exception { //创建HttpGet对象 HttpGet get = new HttpGet(url); //发送GET请求 HttpResponse response = httpClient.execute(get); //若是服务器响应成功 if(response.getStatusLine(). getStatusCode() == 200) { //获取服务器响应的字符串 String result = EntityUtils. toString(response.getEntity()); return result; } return null; } } ); new Thread(task).start(); return task.get(); } /** * * @param url 发送请求的url * @param rawParams 请求参数 * @return 响应的字符串 * @throws Exception */ public static String postRequest(final String url, final Map<String,String> rawParams) throws Exception { // ExecutorService exec=Executors.newCachedThreadPool(); // FutureTask<String> task = new FutureTask<String>( // new Callable<String>() { // @Override // public String call() throws Exception { //创建HttpPost对象 HttpPost post = new HttpPost(new URI(url)); //对较多的传递参数进行封装、 List<NameValuePair> params = new ArrayList<NameValuePair>(); for(String key : rawParams.keySet()) { //封装请求参数 params.add(new BasicNameValuePair(key, rawParams.get(key))); } //设置请求参数 post.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8)); //发送post请求 HttpResponse response = httpClient.execute(post); //若是服务器响应成功 if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ //获取服务器响应的字符串 String result = EntityUtils.toString(response.getEntity(),HTTP.UTF_8); return result; }else{ return "-1"; } } // } // ); // new Thread(task).start(); // return task.get(); // } }
注意:连接本地服务器时,最好使用ipv4地址而不是localhost。
服务端:
写一个servlet接收,判断客户端发送的是什么请求uri
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String uri = request.getRequestURI(); uri = uri.substring(uri.lastIndexOf("/")); System.out.println("uri: " + uri); if("/hotStation.do".equals(uri)) { doHotStationList(request, response); } if("/stationList.do".equals(uri)) { doStationList(request, response); } }
如doHotStationList是这样写的:
public void doHotStationList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=UTF-8"); List<String> hotStationList = StationService.getHostStationList(); JSONArray jsonArray = JSONArray.fromObject(hotStationList); System.out.println("传给客户端:" + jsonArray.toString()); response.getWriter().println(jsonArray.toString()); }
我这里数据交互使用的是json.
客户端获取服务端传递过来的json数据再解析成pojo对象即可。