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

转载 2016年06月01日 16:59:01

现在越来越多的 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"}


HTTP传输byte[ ] 两种方式

//========第一种======== public class HttpUtil { public static InputStream http(String url, byte[] ...

HttpClient Post 二进制/字节流/byte[]

HttpClient 3.x HttpClient 4.x
  • Sidyhe
  • Sidyhe
  • 2016年06月03日 11:28
  • 8897

关于HttpClient post请求 传输json格式的字节流

收集关于httpClient的post请求   好一点的博客 http://blog.sina.com.cn/s/blog_75a8cfac01013aim.html http://b...

从客户端,通过HttpClient发送二进制数据到服务器端

在实现第三方接口时,通过二进制数据通讯,可以更高效、更灵活、更稳定。 从客户端发起请求的代码如下所示。  protected static byte[] remoteInvok...

WebAPI通过multipart/form-data方式同时上传文件以及数据(含HttpClient上传Demo)

简单的Demo,用于了解WebAPI如何同时接收文件及数据,同时提供HttpClient模拟如何同时上传文件和数据的Demo,下面是HttpClient上传的Demo界面 1、HttpCli...
  • starfd
  • starfd
  • 2015年04月30日 13:01
  • 44572

HttpClient(访问网络) get方式,post方式。返回值有String,InputStream,byte[]

import java.io.ByteArrayOutputStream;   import java.io.IOException;   import java.io.InputStream; ...

使用httpclient实现上传下载(javaWeb系统数据传输http实现)

目的:项目被拆分为两个javaWeb项目,实现项目之间数据传输以及上传、下载功能。 题外话: 两个javaWeb传输之间使用json比较方便,如果恰好使用SpringMVC,配置相关JSON转换工具(...

有关使用HTTP协议传输二进制文件

HTTP协议是基于字符(ASCII)的,当Content-Type项为text/xml,则内容是文本格式;当二进制格式时,Content-Type项为image/gif,就是了。例如,浏览器请求一张图...

HttpClient模拟Post请求返回Byte数组

我这里使用的版本是httpclient-4.5版本的。通过Post请求返回Byte数组。对数组进行读就行了 import java.io.IOException; import java.util....

http请求下载文件(byte数组)

/**       * 从网络Url中下载文件       * @param urlStr       * @param fileName       * @param savePath  ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:HttpClient josn网络传输(二进制的byte流)
举报原因:
原因补充:

(最多只允许输入30个字)