现在的位置: 首页 > 移动开发 > 正文

Android 的网络编程(15)-Http JSon服务器端和客户端通信

2019年09月08日 移动开发 ⁄ 共 4875字 ⁄ 字号 评论关闭

Android  Http JSon服务器端和客户端通信 
 服务器端: 

package com.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

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

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.web.model.User;

public class JSONServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public JSONServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
		 
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();

        List<User> list = new ArrayList<User>();
        
        User u1 = new User();
        u1.setId(111);
        u1.setUsername("zhang shan");
        u1.setPassword("zs");
        
        User u2 = new User();
        u2.setId(222);
        u2.setUsername("li si");
        u2.setPassword("ls");
        
        User u3 = new User();
        u3.setId(333);
        u3.setUsername("wang wu");
        u3.setPassword("ww");
        
        list.add(u1);
        list.add(u2);
        list.add(u3);
        
        JSONArray ja = new JSONArray();
        for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			User user = (User) iterator.next();
			JSONObject jobj= new JSONObject();
			jobj.put("id", user.getId());
			jobj.put("username", user.getUsername());
			jobj.put("password", user.getPassword());
			ja.add(jobj);
		}
        
        out.write(ja.toString());   
        out.flush();   
        out.close(); 

	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}

手机端:
package com.web.activity;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod; 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException; 
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.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.web.model.User;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class WebclientActivity extends Activity { 
	private TextView hello;  
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);  
		
		HttpClient httpclient = new DefaultHttpClient();
		String uri="http://10.11.72.108:8086/web/JSONServlet";
		HttpPost httpReqest = new HttpPost(uri);   
		try {  
			HttpResponse response = httpclient.execute(httpReqest);   
			HttpEntity entity = response.getEntity(); 
			BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent())); 
			
			StringBuffer sb = new StringBuffer();     
			String line = null;
	            while ((line = reader.readLine()) != null) {
	                sb.append(line + "\n");
	            }
	            reader.close(); 

		  JSONArray ja = new JSONArray(sb.toString());
		  
		  StringBuffer sb2 = new StringBuffer();
		  for (int i = 0; i < ja.length(); i++) {
			JSONObject jobj= (JSONObject)ja.get(i);
			sb2.append("id:").append(jobj.getInt("id")).append(" ");
            sb2.append("用户:").append(jobj.getString("username")).append(" ");
            sb2.append("密码:").append(jobj.getString("password")).append("\r\n");
		  }
		  
          TextView hello = (TextView) findViewById(R.id.helloid);
		  hello.setText(sb2.toString());

		} catch (Exception e) { 
			Log.i("uuu", e.toString());
		}  
	
    } 
}

抱歉!评论已关闭.