Java HttpServlet Json 数据交互
Android 对其访问进行封装
服务端
package com.server; import java.io.PrintWriter; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONObject; public class LoginServer extends HttpServlet implements java.io.Serializable{ /** * */ private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse res){ String user = request.getParameter("user"); //获取服务端数据 String pass = request.getParameter("pass"); System.out.println(user+pass); //业务逻辑 try{ //中文乱码解决 res.setContentType("text/html;charset=gbk"); PrintWriter pw = res.getWriter(); //返回Json数据
JSONObject jsonObj = new JSONObject().put("userId" , 1); pw.println(jsonObj.toString()); } catch(Exception ex){ ex.printStackTrace(); } } public void doPost(HttpServletRequest req, HttpServletResponse res){ this.doGet(req, res); } }
web.xml
<servlet> <!--给survlet起个名字,可以是任意的 --> <servlet-name>LoginServer</servlet-name> <!--servlet的路径(包名+类名) --> <servlet-class>com.server.LoginServer</servlet-class> </servlet> <servlet-mapping> <!-- servlet的名字和上面保持统一 --> <servlet-name>LoginServer</servlet-name> <!-- 这是在浏览器中输入的访问该survlet的url,任意的 --> <url-pattern>/login</url-pattern> </servlet-mapping>
客户端通过Json获取服务端数据
/** * */ package org.crazyit.auction.client.util; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; /** * Description: * <br/>网站: <a href="http://www.crazyit.org">疯狂ava联盟</a> * <br/>Copyright (C), 2001-2014, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ public class HttpUtil { // 创建HttpClient对象 public static HttpClient httpClient = new DefaultHttpClient(); /** * * @param url 发送请求的URL * @return 服务器响应字符串 * @throws Exception */ 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 httpResponse = httpClient.execute(get); // 如果服务器成功地返回响应 if (httpResponse.getStatusLine() .getStatusCode() == 200) { // 获取服务器响应字符串 String result = EntityUtils .toString(httpResponse.getEntity()); return result; } return null; } }); new Thread(task).start(); return task.get(); } /** * @param url 发送请求的URL * @param params 请求参数 * @return 服务器响应字符串 * @throws Exception */ public static String postRequest(final String url , final Map<String ,String> rawParams)throws Exception { FutureTask<String> task = new FutureTask<String>( new Callable<String>() { @Override public String call() throws Exception { // 创建HttpPost对象。 HttpPost post = new HttpPost(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, "gbk")); // 发送POST请求 HttpResponse httpResponse = httpClient.execute(post); // 如果服务器成功地返回响应 if (httpResponse.getStatusLine() .getStatusCode() == 200) { // 获取服务器响应字符串 String result = EntityUtils .toString(httpResponse.getEntity()); return result; } return null; } }); new Thread(task).start(); return task.get(); } }
Callable是类似于Runnable的接口,实现Callable接口的类和实现Runnable的类都是可被其它线程执行的任务。
Callable和Runnable有几点不同:
(1)Callable规定的方法是call(),而Runnable规定的方法是run().
(2)Callable的任务执行后可返回值,而Runnable的任务是不能返回值的。
(3)call()方法可抛出异常,而run()方法是不能抛出异常的。
(4)运行Callable任务可拿到一个Future对象,
Future 表示异步计算的结果。它提供了检查计算是否完成的方法,以等待计算的完成,并检索计算的结果。
通过Future对象可了解任务执行情况,可取消任务的执行,还可获取任务执行的结果。
测试
public class test { public static void main(String []main){ Map<String, String> map = new HashMap<String, String>(); map.put("user", "user"); map.put("pass", "pass"); // 定义发送请求的URL String url = "http://localhost:8080/HttpServletServer/login"; // 发送请求 try { System.out.println(HttpUtil.postRequest(url, map)); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }; } }
- 引用的包的下载地址 :http://download.csdn.net/download/huhuan19890427/6608621