利用java中的HttpUrlConnection上传文件,我们其实只要知道Http协议上传文件的标准格式。那么就可以用任何一门语言来模拟浏览器上传文件。下面有几篇文章从http协议入手介绍了java中上传文件.

下面分享一个自己封装的http工具类(暂不直接支持文件上传)------没有引入任何地三方jar包

1 HttpRequest类

package com.yy.game.risecloud.sdk.common.model;

import java.util.Map;

/**
 * http请求类
 *
 * @author zhuhui
 *
 */
public class HttpRequest {
	/**
	 * http请求编码,默认UTF-8
	 */
	public String charsetName = RisecloudSdkConstant.CHARSET_NAME;
	/**
	 * HTTP请求超时时间,默认5000ms
	 */
	public int timeout = RisecloudSdkConstant.HTTP_REQUEST_TIMEOUT;
	/***
	 * http请求url地址
	 */
	public String url;
	/***
	 * http请求方法,只支持GET,POST,PUT,DELETE
	 */
	public HttpMethod method;
	/***
	 * http请求消息报头
	 */
	public Map<String, String> headers;
	/**
	 * http请求url参数
	 */
	public Map<String, String> params;
	/***
	 * http请求正文内容
	 */
	public String content;

	public HttpRequest() {

	}

	public HttpRequest(String url, HttpMethod method) {
		this.url = url;
		this.method = method;
	}

	public HttpRequest(String url, HttpMethod method, Map<String, String> headers) {
		this(url, method);
		this.headers = headers;
	}

	public HttpRequest(String url, HttpMethod method, Map<String, String> headers, Map<String, String> params) {
		this(url, method, headers);
		this.params = params;
	}

	public HttpRequest(String url, HttpMethod method, Map<String, String> headers, String content) {
		this(url, method, headers);
		this.content = content;
	}
}

2. HttpResponse类

package com.yy.game.risecloud.sdk.common.model;
/**
 * http响应类
 * @author zhuhui
 *
 */
public class HttpResponse {
	/**
	 * http响应状态码
	 */
	public int code;
	/**
	 * 与响应代码一起返回的 HTTP 响应消息
	 */
	public String message;
	/**
	 * 响应正文内容
	 */
	public String content;

	public HttpResponse(int code, String message, String content) {
		this.code = code;
		this.message = message;
		this.content = content;
	}
}

3.用到的工具方法(可能直接拷贝有问题,去掉出错的代码就可以了)

package com.yy.game.risecloud.sdk.common.internal;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;

import com.yy.game.risecloud.sdk.common.model.RisecloudSdkConstant;

/**
 * 常用工具类
 *
 * @author zhuhui
 */
public class CommonUtil {
	private CommonUtil() {

	}

	/**
	 * 判断字符串是否为空
	 *
	 * @param s
	 * @return 如果字符串为空或者字符串去除首尾空格为空字符串则返回true,反之返回false
	 */
	public static boolean isEmpty(String s) {
		if (s == null || s.trim().length() == 0) {
			return true;
		}
		return false;
	}

	/**
	 * 判断map是否为空
	 *
	 * @param map
	 *            map对象
	 * @return 如果map==null或者map.size()==0则返回true,反之返回false
	 */
	@SuppressWarnings("all")
	public static boolean isEmpty(Map map) {
		if (map == null || map.size() == 0) {
			return true;
		}
		return false;
	}

	/***
	 * 判断list是否为空
	 *
	 * @param list
	 *            list对象
	 * @return 如果list==null或者list.size==则返回true,反之返回false
	 */
	@SuppressWarnings("all")
	public static boolean isEmpty(List list) {
		if (list == null || list.size() == 0) {
			return true;
		}
		return false;
	}

	/**
	 * 将map转成http url请求参数的格式
	 *
	 * @param map
	 * @return map为空返回null,反之返回类似name=zhangsan&age=14的这样的格式
	 */
	public static String map2UrlParams(Map<String, String> map) {
		if (isEmpty(map)) {
			return null;
		}
		StringBuilder sb = new StringBuilder();
		for (Entry<String, String> entry : map.entrySet()) {
			if (!isEmpty(entry.getValue())) {
				String key = entry.getKey();
				try {
					String value = URLEncoder.encode(entry.getValue(), "UTF-8");
					sb.append("&" + key + "=" + value);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		if (sb.length() > 0) {
			return sb.substring(1);
		}
		return null;
	}

	public static String uuid() {
		return UUID.randomUUID().toString();
	}

	public static String deleteWhitespace(String str) {
        if (isEmpty(str)) {
            return str;
        }
        int sz = str.length();
        char[] chs = new char[sz];
        int count = 0;
        for (int i = 0; i < sz; i++) {
            if (!Character.isWhitespace(str.charAt(i))) {
                chs[count++] = str.charAt(i);
            }
        }
        if (count == sz) {
            return str;
        }
        return new String(chs, 0, count);
    }

	public static Map<String, String> auth(String token) {
		Map<String, String> header = new HashMap<String, String>();
		header.put(RisecloudSdkConstant.HEAD_X_AUTH_TOKEN, token);
		return header;
	}
}

4 HttpMethod

package com.yy.game.risecloud.sdk.common.model;

/**
 * http请求方法枚举类
 *
 * @author zhuhui
 *
 */
public enum HttpMethod {
	GET, POST, PUT, DELETE;
}

5 HttpUtil类

package com.yy.game.risecloud.sdk.common.internal;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import com.yy.game.risecloud.sdk.common.model.HttpMethod;
import com.yy.game.risecloud.sdk.common.model.HttpRequest;
import com.yy.game.risecloud.sdk.common.model.HttpResponse;

public class HttpUtil {
	private HttpUtil() {

	}

	static HostnameVerifier sslHostnameVerifier;

	static synchronized void initSslHostnameVerifier() {
		if (sslHostnameVerifier != null) {
			return;
		}
		sslHostnameVerifier = new HostnameVerifier() {
			public boolean verify(String urlHostName, SSLSession session) {
				return urlHostName != null && urlHostName.equals(session.getPeerHost());
			}
		};
	}

	static SSLSocketFactory sslSocketFactory;

	/**
	 * 忽略SSL证书
	 */
	static synchronized void initSslSocketFactory() {
		if (sslSocketFactory != null) {
			return;
		}
		InputStream in = null;
		try {
			SSLContext context = SSLContext.getInstance("TLS");
			final X509TrustManager trustManager = new X509TrustManager() {
				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}

				public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
				}

				public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

				}
			};
			context.init(null, new TrustManager[] { trustManager }, null);
			sslSocketFactory = context.getSocketFactory();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	private static HttpURLConnection createConnection(String url) throws Exception {
		HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
		if ("https".equalsIgnoreCase(url.substring(0, 5))) {
			if (sslSocketFactory == null) {
				initSslSocketFactory();
			}
			((HttpsURLConnection) conn).setSSLSocketFactory(sslSocketFactory);
			if (sslHostnameVerifier == null) {
				initSslHostnameVerifier();
			}
			((HttpsURLConnection) conn).setHostnameVerifier(sslHostnameVerifier);
		}
		conn.setUseCaches(false);
		conn.setInstanceFollowRedirects(true);
		conn.setRequestProperty("Connection", "close");
		return conn;
	}

	public static HttpResponse execute(HttpRequest request) throws Exception {
		/* 参数检查 */
		if (request == null) {
			throw new IllegalArgumentException("HttpRequest must be not null");
		}
		if (CommonUtil.isEmpty(request.url)) {
			throw new IllegalArgumentException("HttpRequest url must be not null");
		}
		if (request.timeout < 0) {
			throw new IllegalArgumentException(String.format("timeout=[%s],HttpRequest timeout must be Greater than zero", request.timeout + ""));
		}
		if (request.method == HttpMethod.GET && !CommonUtil.isEmpty(request.content)) {
			throw new IllegalArgumentException("When Http Method is GET,the HttpRquest content must be null");
		}
		HttpURLConnection connection = null;
		String url = request.url;
		try {
			// 设置url传递参数
			if (!CommonUtil.isEmpty(request.params)) {
				String queryString = CommonUtil.map2UrlParams(request.params);
				if (!CommonUtil.isEmpty(queryString)) {
					url = url + "?" + queryString;
				}
			}
			// 获取连接
			connection = createConnection(url);
			connection.setRequestMethod(request.method.toString());
			connection.setConnectTimeout(request.timeout);
			connection.setDoOutput(true);
			connection.setDoInput(true);
			// 设置请求头
			if (!CommonUtil.isEmpty(request.headers)) {
				for (Map.Entry<String, String> entry : request.headers.entrySet()) {
					connection.setRequestProperty(entry.getKey(), entry.getValue());
				}
			}
			connection.connect();
			// 设置请求正文
			if (!CommonUtil.isEmpty(request.content)) {
				DataOutputStream out = new DataOutputStream(connection.getOutputStream());
				out.write(request.content.getBytes(request.charsetName));
				out.close();
			}
			int code = connection.getResponseCode();
			String message = connection.getResponseMessage();
			StringBuilder result = new StringBuilder();
			InputStream in = connection.getErrorStream();
			if (in == null) {
				in = connection.getInputStream();
			}
			if (in != null) {
				BufferedReader reader = new BufferedReader(new InputStreamReader(in));
				char[] cbuf = new char[4096];
				while (true) {
					int len = reader.read(cbuf);
					if (len < 0) {
						break;
					}
					result.append(cbuf, 0, len);
				}
			}
			return new HttpResponse(code, message, result.toString());
		} catch (Exception e) {
			throw e;
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
	}
}
 

java http工具类和HttpUrlConnection上传文件分析的更多相关文章

  1. Android端通过HttpURLConnection上传文件到服务器

    Android端通过HttpURLConnection上传文件到服务器 一:实现原理 最近在做Android客户端的应用开发,涉及到要把图片上传到后台服务器中,自己选择了做Spring3 MVC HT ...

  2. Android端通过HttpURLConnection上传文件到server

    Android端通过HttpURLConnection上传文件到server 一:实现原理 近期在做Androidclient的应用开发,涉及到要把图片上传到后台server中.自己选择了做Sprin ...

  3. HttpURLConnection上传文件

    HttpURLConnection上传文件 import java.io.BufferedReader; import java.io.DataInputStream; import java.io. ...

  4. Java使用HttpURLConnection上传文件

    从普通Web页面上传文件非常easy.仅仅须要在form标签叫上enctype="multipart/form-data"就可以,剩余工作便都交给浏览器去完毕数据收集并发送Http ...

  5. Java使用HttpURLConnection上传文件(转)

    从普通Web页面上传文件很简单,只需要在form标签叫上enctype="multipart/form-data"即可,剩余工作便都交给浏览器去完成数据收集并发送Http请求.但是 ...

  6. Java EE之通过表单上传文件

    public class Ticket { private String customerName; private String subject; private String body; priv ...

  7. Java如何解决form表单上传文件,以及页面返回处理结果通知!

    前端JSP代码 <form id='formSumbit' class='form-horizontal' action='/ncpay/route/chlsubmcht/batchImpor' ...

  8. java 模拟表单方式提交上传文件

    /** * 模拟form表单的形式 ,上传文件 以输出流的形式把文件写入到url中,然后用输入流来获取url的响应 * * @param url 请求地址 form表单url地址 * @param f ...

  9. C# ICSharpCode.SharpZipLib.dll文件压缩和解压功能类整理,上传文件或下载文件很常用

    工作中我们很多时候需要进行对文件进行压缩,比较通用的压缩的dll就是ICSharpCode.SharpZipLib.dll,废话不多了,网上也有很多的资料,我将其最常用的两个函数整理了一下,提供了一个 ...

随机推荐

  1. jQuery手机菜单

      效果展示 http://hovertree.com/texiao/nav/4/ 手机扫描二维码查看效果: 源码下载 http://hovertree.com/h/bjaf/kroft6c7.htm ...

  2. 【C#进阶系列】30 学习总结

    前面学起来还是很顺的,毕竟很多都接触过. 后面学起来只能用“磨”来形容,以至于八章用了2个月.(当然也有相当一些原因是这两个月中发生了一些个人生活上的问题) 总的来说收获超大,这种感觉就像大一的时候学 ...

  3. 【nodejs笔记1】配置webstorm + node.js +express + mongodb开发博客的环境

    1. 安装webstorm 并破解 2. 安装node (以及express框架) 至官网下载并安装.(http://nodejs.org)v0.10.32   msi  安装后测试,打开命令行, c ...

  4. 数据结构:链表(python版) 续:增加比较函数

    题目: 基于元素相等操作"=="定义一个单链表的相等比较函数.另请基于字典序的概念,为链表定义大于,小于,大于等于,小于等于的判断 class LList: "" ...

  5. Verilog HDL模型的不同抽象级别

    所谓不同的抽象类别,实际上是指同一个物理电路,可以在不同层次上用Verilog语言来描述.如果只从行为功能的角度来描述某一电路模块,就称作行为模块.如果从电路结构的角度来描述该电路模块,就称作结构模块 ...

  6. 如何寻找“真爱”型合伙人

          曾与朋友笑侃,现在找人结婚,跟合伙开公司差不多,各自条件一一对比,细细斟酌,最后双方达成一致,才得凑成一对冤家.谁说不是呢?两种关系都实为"伙伴",开公司重" ...

  7. HashTable(散列表)

    最近都在研究数据结构,关于hashtable,或者叫做散列表,过去一直不了解是什么东西,现在终于明白了. 所谓hashtable,就是某组key,通过某个关系(函数),得到一个与之对应的映射值(在计算 ...

  8. Docker化运维方式讲解

    应用迁移需求 应用运维需要考虑的一个重要问题就是迁移, 在不同机器.机房.环境间迁移.迁移的原因有很多, 比如硬件过保(硬件故障), 机房迁移, 应用扩缩容等. 应用迁移的核心需求是: 简单.迁移操作 ...

  9. ipa如何通过网络进行安装

    苹果手机端应用,如果发布的到Appstore上,往往比较复杂,周期也比较长,Over-the-Air是Apple在 iOS4 中新加的一项技术,目的是让开发者能够脱离Appstore,实现从自己的服务 ...

  10. jquery自定义对话框alert、confirm和prompt

    jQuery Alert Dialogs,又一个基于jQuery的提示框插件,主要包括Alert.Confirm.prompt这三种,还有一个高级范例,可以在提示框内嵌入HTML语言,可以自定义风格样 ...