Java 发送 get, post 请求

花了一天时间,基于Java 的 HttpURLConnection 和JDK 1.8的Base64写了个发送get 和post请求的工具类。本工具类有get和post两个方法,使用时只需

String result = HttpUtils.get(url, args);

String result = HttpUtils.post(url, args);

即可获取返回结果。

参数说明:

url: 请求的服务器地址;

args: Map<String, Object> 类型的参数,参数可以是Java的基本类型,基本类型包装类,String,File,InputStream

注意:发送文件时,文件最好控制在5M以内,由于采用Base64编解码,文件太大会造成内存溢出。

源码:


package test;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

/**
 * @ClassName: HttpUtils
 * @Description: Http 请求工具类
 * @author lixk
 * @date 2017年3月31日 下午6:21:20
 * @version [1.0, 2017年3月31日]
 * @since version 1.0
 */
public class HttpUtils {

	/**
	 * 
	 * @Title: get
	 * @Description: 向服务器发起get请求
	 * @param url
	 *            请求地址
	 * @param args
	 *            请求参数
	 * @return 字符串格式的服务器响应数据
	 * @throws IOException
	 */
	public static String get(String url, Map<String, Object> args) throws IOException {
		// 请求服务器的地址
		StringBuilder fullHostUrl = new StringBuilder(url).append("?");

		// 如果参数不空,循环遍历参数
		if (args != null) {
			for (Entry<String, Object> entry : args.entrySet()) {
				String key = entry.getKey(); // 参数名称
				Object value = entry.getValue(); // 参数值

				// 如果是文件格式参数,获取文件数据流
				if (value instanceof File) {
					value = new FileInputStream(File.class.cast(value));
				}
				// 数据流参数
				if (value instanceof InputStream) {
					fullHostUrl.append(key).append("=");
					InputStream is = InputStream.class.cast(value);
					byte[] data = new byte[is.available()];
					is.read(data);
					fullHostUrl.append(URLEncoder.encode(Base64.getEncoder().encodeToString(data), "UTF-8"));
					// 关闭输入流
					is.close();
				} else { // 其他类型参数
					fullHostUrl.append(key).append("=").append(URLEncoder.encode(String.valueOf(value), "UTF-8"));
				}
				// 参数结尾加连接符
				fullHostUrl.append("&");
			}
		}

		URL host = new URL(fullHostUrl.toString());
		HttpURLConnection connection = HttpURLConnection.class.cast(host.openConnection());
		// 设置为GET请求
		connection.setRequestMethod("GET");
		// 禁用缓存
		connection.setUseCaches(false);
		// 设置请求头参数
		connection.setRequestProperty("Connection", "Keep-Alive");
		connection.setRequestProperty("Charsert", "UTF-8");

		// 通过输入流来读取服务器响应
		int resultCode = connection.getResponseCode();
		StringBuilder response = new StringBuilder();
		if (resultCode == HttpURLConnection.HTTP_OK) {
			BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = br.readLine()) != null) {
				response.append(line);
			}
			// 关闭输入流
			br.close();
		} else {
			response.append(resultCode);
		}
		return response.toString();
	}

	/**
	 * 
	 * @Title: post
	 * @Description: 向服务器发起post请求
	 * @param url
	 *            请求地址
	 * @param args
	 *            请求参数
	 * @return 字符串格式的服务器响应数据
	 * @throws IOException
	 */
	public static String post(String url, Map<String, Object> args) throws IOException {
		// 请求服务器的地址
		URL host = new URL(url);
		HttpURLConnection connection = HttpURLConnection.class.cast(host.openConnection());
		// 设置为POST请求
		connection.setRequestMethod("POST");
		// 发送POST请求必须设置如下两行
		connection.setDoOutput(true);
		connection.setDoInput(true);
		// 禁用缓存
		connection.setUseCaches(false);
		// 设置请求头参数
		connection.setRequestProperty("Connection", "Keep-Alive");
		connection.setRequestProperty("Charsert", "UTF-8");
		// 获取数据输出流
		DataOutputStream dos = new DataOutputStream(connection.getOutputStream());

		// 如果参数不空,循环遍历参数
		if (args != null) {
			for (Entry<String, Object> entry : args.entrySet()) {
				String key = entry.getKey(); // 参数名称
				Object value = entry.getValue(); // 参数值

				// 如果是文件格式参数,获取文件数据流
				if (value instanceof File) {
					value = new FileInputStream(File.class.cast(value));
				}
				// 数据流参数
				if (value instanceof InputStream) {
					dos.write((key + "=").getBytes());
					InputStream is = InputStream.class.cast(value);
					byte[] data = new byte[is.available()];
					is.read(data);
					dos.write(URLEncoder.encode(Base64.getEncoder().encodeToString(data), "UTF-8").getBytes());
					// 关闭输入流
					is.close();
				} else { // 其他类型参数
					dos.write((key + "=" + URLEncoder.encode(String.valueOf(value), "UTF-8")).getBytes());
				}
				// 参数结尾加连接符
				dos.write("&".getBytes());
			}
		}
		// 关闭输出流
		dos.flush();
		dos.close();

		// 通过输入流来读取服务器响应
		int resultCode = connection.getResponseCode();
		StringBuilder response = new StringBuilder();
		if (resultCode == HttpURLConnection.HTTP_OK) {
			BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = br.readLine()) != null) {
				response.append(line);
			}
			// 关闭输入流
			br.close();
		} else {
			response.append(resultCode);
		}
		return response.toString();
	}

	public static void main(String[] args) throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("transtype", "translang");
		map.put("textFile", new File("java并发编程的艺术.pdf"));
		map.put("textFileName", "java并发编程的艺术.pdf");
		map.put("photo", new File("2.jpg"));
		map.put("photoName", "照片.jpg");
		System.out.println(HttpUtils.post("http://localhost/test", map));
	}

}

服务器端测试代码:

package test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Base64;

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

@WebServlet("/test")
public class HttpUtilsTest extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		String textFileName = request.getParameter("textFileName"); // 文件名
		String textFile = request.getParameter("textFile"); // 文件
		FileOutputStream textOS = new FileOutputStream("C:/data/" + textFileName);
		textOS.write(Base64.getDecoder().decode(textFile));
		textOS.close();

		String photoName = request.getParameter("photoName"); // 图片名称
		String photo = request.getParameter("photo"); // 图片文件
		FileOutputStream photoOS = new FileOutputStream("C:/data/" + photoName);
		photoOS.write(Base64.getDecoder().decode(photo));
		photoOS.close();
		PrintWriter out = response.getWriter();
		out.write("文件上传成功!");
	}
}


结果预览:



源码下载:http://download.csdn.net/detail/u013314786/9801676

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值