原始java写的模拟HTTP请求 HttpsMethod

原始java写的模拟HTTP请求

package com.fc.utility;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.CharBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.b3log.latke.Keys;
import org.b3log.latke.model.User;
import org.b3log.latke.util.CollectionUtils;
import org.b3log.latke.util.Sessions;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * the https method
 * 
 * */
public class HttpsMethod {

	/**
	 * post方法
	 * 
	 * @param url
	 *            String 访问的URL
	 * @param param
	 *            String 提交的内容
	 * @param repType
	 *            返回类型
	 * @return String
	 * */
	public static String postRequest(String url, String param, String repType) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			/**
			 * 第一部分
			 */
			URL urlObj = new URL(url);
			HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();

			/**
			 * 设置关键值
			 */
			con.setRequestMethod("POST"); // 以Post方式提交表单,默认get方式
			con.addRequestProperty("Accept-Language", "zh-cn");
			con.addRequestProperty("Content-type", repType);
			con.addRequestProperty(
					"User-Agent",
					"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727)");
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false); // post方式不能使用缓存

			// 设置请求头信息
			con.setRequestProperty("Connection", "Keep-Alive");
			con.setRequestProperty("Charset", "UTF-8");

			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(con.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(con.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常!" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * get方法提交
	 * 
	 * @param url
	 *            String 访问的URL
	 * @param param
	 *            String 提交的内容
	 * @param repType
	 *            返回类型
	 * @return String
	 * */
	public static byte[] getRequest(String url, String repType) {
		String result = "";
		byte[] resByt = null;
		try {
			URL urlObj = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) urlObj
					.openConnection();

			// 连接超时
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setConnectTimeout(25000);

			// 读取超时 --服务器响应比较慢,增大时间
			conn.setReadTimeout(25000);
			conn.setRequestMethod("GET");

			conn.addRequestProperty("Accept-Language", "zh-cn");
			conn.addRequestProperty("Content-type", repType);
			conn.addRequestProperty(
					"User-Agent",
					"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727)");
			conn.connect();

			PrintWriter out = new PrintWriter(new OutputStreamWriter(
					conn.getOutputStream(), "UTF-8"), true);

			if ("image/jpeg".equals(repType)) {
				ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
				BufferedImage bufImg = ImageIO.read(conn.getInputStream());
				ImageIO.write(bufImg, "jpg", outputStream);
				resByt = outputStream.toByteArray();
				outputStream.close();

			} else {
				// 取得输入流,并使用Reader读取
				System.out.println("set utf-8 decode...");
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(conn.getInputStream(), "utf-8"));

				System.out.println("=============================");
				System.out.println("Contents of get request");
				System.out.println("=============================");
				String lines = null;
				while ((lines = reader.readLine()) != null) {
					System.out.println(lines);
					result += lines;
					result += "\r";
				}
				resByt = result.getBytes();
				reader.close();
			}
			out.print(resByt);
			out.flush();
			out.close();
			// 断开连接
			conn.disconnect();
			System.out.println("=============================");
			System.out.println("Contents of get request ends");
			System.out.println("=============================");
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return resByt;
	}

	public static String fileUploadReuest(String url, String filePath,
			String repType) {
		String result = "";
		File file = new File(filePath);
		try {
			/**
			 * 第一部分
			 */
			URL urlObj = new URL(url);
			HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();

			/**
			 * 设置关键值
			 */
			con.setRequestMethod("POST"); // 以Post方式提交表单,默认get方式
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false); // post方式不能使用缓存

			// 设置请求头信息
			con.setRequestProperty("Connection", "Keep-Alive");
			con.setRequestProperty("Charset", "UTF-8");

			// 设置边界
			String BOUNDARY = "----------" + System.currentTimeMillis();
			con.setRequestProperty("Content-Type",
					"multipart/form-data; boundary=" + BOUNDARY);

			// 请求正文信息

			// 第一部分:
			StringBuilder sb = new StringBuilder();
			sb.append("--"); // 必须多两道线
			sb.append(BOUNDARY);
			sb.append("\r\n");
			sb.append("Content-Disposition: form-data;name=\"file\";filename=\""
					+ file.getName() + "\"\r\n");
			sb.append("Content-Type:application/octet-stream\r\n\r\n");

			byte[] head = sb.toString().getBytes("utf-8");

			// 获得输出流

			OutputStream out = new DataOutputStream(con.getOutputStream());
			out.write(head);

			// 文件正文部分
			DataInputStream in = new DataInputStream(new FileInputStream(file));
			int bytes = 0;
			byte[] bufferOut = new byte[1024];
			while ((bytes = in.read(bufferOut)) != -1) {
				out.write(bufferOut, 0, bytes);
			}
			in.close();

			// 结尾部分
			byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线

			out.write(foot);
			out.flush();
			out.close();

			/**
			 * 读取服务器响应,必须读取,否则提交不成功
			 */
			// return con.getResponseCode();
			/**
			 * 下面的方式读取也是可以的
			 */
			// 定义BufferedReader输入流来读取URL的响应
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					con.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				result += line;
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NullPointerException e) {
			// TODO: handle exception
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	public static Map<String, String> parseXml(HttpServletRequest req) {
		Map<String, String> map = new HashMap<String, String>();

		InputStream inputStream = null;
		try {
			inputStream = req.getInputStream();
			SAXReader reader = new SAXReader();

			Document document;
			document = reader.read(inputStream);

			Element root = document.getRootElement();
			List<Element> elementList = root.elements();
			for (Element e : elementList)
				map.put(e.getName(), e.getText());
		} catch (Exception e1) {
			e1.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
				}
			}
		}

		return map;
	}

	public static String formatRequestToKey(HttpServletRequest req,
			String templateName) {

		Object[] keys = null;
		Enumeration e = req.getAttributeNames();

		List<String> vs = new ArrayList<String>();
		while (e.hasMoreElements()) {
			String key = e.nextElement().toString();
			if (!StringUtils.isEmpty(key)) {
				vs.add(key);
			}
		}
		keys = vs.toArray();
		Arrays.sort(keys);

		String url = req.getRequestURL().toString();
		String uuid = "";
		for (int j = 0; j < keys.length; j++) {
			uuid += keys[j] + ":" + req.getParameter(keys[j].toString()) + "-";
		}

		String userUUID = "";
		HttpSession session = Sessions.getSession(req);
		if (session != null) {
			Object user = session.getAttribute(User.USER);
			if (user != null) {
				try {
					userUUID = ((JSONObject) user).getString(Keys.OBJECT_ID);
				} catch (JSONException e1) {
				}
			}
		}
		uuid = url + uuid + userUUID;

		if (!StringUtils.isEmpty(templateName)) {
			uuid += "/" + templateName;
		}

		return uuid;
	}
}

 

 

 

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值