客户端和应用服务器之间利用HttpClient和Servlet交互JSON对象进行通信

记录下最近研究的关于如何在Android 应用程序和服务器之间通信的方法。

环境:

1.应用服务器Tomcat http://tomcat.apache.org

2.客户端 HttpClient http://hc.apache.org/httpcomponents-client-ga/index.html

3.GSON http://code.google.com/p/google-gson/


/**
 * Example servlet showing how to exchange JSON obj between servlet and HttpClient
 *
 * @author sureone@yeah.net
 */
/* The data Object sent over Server and Client */
public class Login{
	public int mCode=0;
	public String mResult=null;
	public String mAcc=null;
	public String mPwd=null;
	public Login(String acc,String pwd){
		mAcc = acc;
		mPwd = pwd;
	}
};
/* Servlet Code */

import java.io.*;
import com.google.gson.Gson;
import com.wcare.object.*;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.ResourceBundle;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class WCS extends HttpServlet {

    private static final long serialVersionUID = 1L;

    private static final ResourceBundle RB = ResourceBundle.getBundle("LocalStrings");
    
    @Override
    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException
    {
			getServletContext().log("doGet"); 
    }

    @Override
    public void doPost(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException
    {
			getServletContext().log("doPost"); 
			StringBuffer jb = new StringBuffer();
			String line = null;
			Gson gson = new Gson();
			try {
			    BufferedReader reader = request.getReader();
			    while ((line = reader.readLine()) != null)
			          jb.append(line);
			} catch (Exception e) { e.printStackTrace(); }
			Login objLogin = (Login)(gson.fromJson(jb.toString(),Login.class));
			getServletContext().log("doPost:"+objLogin.mAcc+","+objLogin.mPwd); 
			objLogin.mCode=200;
			objLogin.mResult="Success";
			response.setContentType("application/json");
			// Get the printwriter object from response to write the required json object to the output stream      
			PrintWriter out = response.getWriter();
			out.print(gson.toJson(objLogin));
			out.flush();

    }

}
/* Client Code */
import java.io.*;
import java.net.Socket;
import com.google.gson.Gson;
import org.apache.http.entity.StringEntity;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ResponseHandler;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.NameValuePair;
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.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.http.client.HttpClient;
import org.apache.http.message.BasicHeader;


public class Main{
	public static final String URL="http://127.0.0.1:8080/examples/wcs";
	public static void main(String[] args) throws Exception {
		new Main().doTest();
	}
	public void doTest(){
		Login objLogin= new Login("Li","123");	
		Gson gson = new Gson();
		String json = gson.toJson(objLogin);
		System.out.println(json);
		int i=0;
		do{
			PostThread t = new PostThread(json,URL);
			new Thread(t).start();
			i++;
		}while(i<100);
	}
	public static void doPost(String url, String sjson) throws Exception 
	{
	    HttpClient httpclient = new DefaultHttpClient();
	    HttpPost request = new HttpPost(url);
	    HttpEntity entity;
	    Gson gson = new Gson();
	    StringEntity s = new StringEntity(sjson);
	    s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
	    entity = s;
	    request.setEntity(entity);
	    ResponseHandler<String> responseHandler=new BasicResponseHandler();
	    String responseBody = httpclient.execute(request, responseHandler);
	    System.out.println(responseBody);
	    Login objLogin = gson.fromJson(responseBody,Login.class);
	    System.out.println("RESPONSE:"+objLogin.mCode+","+objLogin.mResult);
	    //JSONObject response=new JSONObject(responseBody);
	}
	class PostThread implements Runnable {
	  String sjson;
	  String url;
	  public PostThread(String s,String u) { sjson=s;url=u;}
	  public void run() { // thread dies when finished
		try{
		doPost(url,sjson);
		}catch(Exception e){e.printStackTrace();}
	  }
        }
}



            
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭