关闭

HttpClient josn网络传输(二进制的byte流)

2296人阅读 评论(0) 收藏 举报
分类:

现在越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源

Client客户端:

package httpjson;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.log4j.Logger;
import org.junit.Test;


public class ClientDemo {

	private final static Logger _log = Logger.getLogger(ClientDemo.class);

	@Test
	public void login(){
		String url = "http://192.168.0.3:8081/httpjson/demoHttpJson" ;
	//	String url = "http://www.weibo.com.cn" ;
		JSONObject json = new JSONObject();
		json.put("username","test");
		json.put("password", "test");
		doPostClient(json, url);
	}

	@SuppressWarnings("deprecation")
	public static void doPostClient(JSONObject json ,String url){
		
		HttpClient httpClient = new HttpClient();
		//httpClient.getState().setCookiePolicy(CookiePolicy.COMPATIBILITY);
		System.setProperty("apache.commons.httpclient.cookiespec","COMPATIBILITY");
		PostMethod postMethod = new PostMethod(url);
		InputStream  in = new ByteArrayInputStream(json.toString().getBytes());
		postMethod.setRequestBody(in);
		HttpClientParams params = new HttpClientParams();
		params.setConnectionManagerTimeout(10000L);
		httpClient.setParams(params);
		try {
			httpClient.executeMethod(postMethod);
			//获取二进制的byte流
			byte[] b = postMethod.getResponseBody();
			String str = new String(b,"UTF-8");
			_log.debug("client:"+str);
		}catch (Exception e) {
			// TODO: handle exception
			System.out.println(e.getMessage()+","+e.getStackTrace());
		}finally{
			postMethod.releaseConnection();
		}
	}
	
}

Service 服务端:

package httpjson;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

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

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

/**
 * Servlet implementation class DemoHttpJson
 */
public class DemoHttpJson extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private final static Logger _log = Logger.getLogger(HttpJsonUtil.class);
    /**
     * Default constructor. 
     */
    public DemoHttpJson() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		// TODO Auto-generated method stub
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletInputStream servletInputStream = request.getInputStream();
		ByteArrayOutputStream  out = new ByteArrayOutputStream ();
		byte[] b = new byte[1024];
		int i = 0;
		// inputStream 转 byte
		while((i = servletInputStream.read(b,0,1024))>0){
			out.write(b,0,i);
		}
		
		byte[] req = out.toByteArray();
		
		String str = new String(req,"UTF-8");
		JSONObject reqJson = JSONObject.fromObject(str);
		JSONObject json = new JSONObject();
		json.put("VER","1.0");
		if(reqJson.get("username").equals("demo")){
			json.put("msg","true");
			_log.debug("登录成功");
		}else{
			json.put("msg","false");
			_log.debug("登录失败");
		}
		
		PrintWriter pw = response.getWriter();
		pw.write(json.toString());
	}

}
执行  public void login()
控制台日志

service log
[11/10/11 00:09:48] [DemoHttpJson-DEBUG 64] 登录失败


client log
[11/10/11 00:09:48] [ClientDemo-DEBUG 46] client:
{"VER":"1.0","msg":"false"}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:844700次
    • 积分:13137
    • 等级:
    • 排名:第1077名
    • 原创:415篇
    • 转载:584篇
    • 译文:6篇
    • 评论:49条
    文章分类
    最新评论