HttpURLConnection模拟Http操作 并自定义http请求

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class TestCustomHttp {
	// 255473522
	public static void main(String[] args) throws Exception {

		// customrequestget(
		// "https://api.douban.com/v2/note/user_created/52441987", null,
		// "GET");
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("title", "ghr更改tesdfsdsadasdasdasdfst");
		map.put("privacy", "");
		map.put("can_reply", "");
		map.put("content", "46546546546546dsfdsf54");
		customrequest("https://api.douban.com/v2/note/255650740", map, "PUT");

	}

	/**
	 * 自定义的http请求可以设置为DELETE PUT等而不是GET
	 * 
	 * @param url
	 * @param params
	 * @param method
	 * @throws IOException
	 */
	public static void customrequest(String url,
			HashMap<String, String> params, String method) throws IOException {
		// Post请求的url,与get不同的是不需要带参数
		URL postUrl = new URL(url);
		// 打开连接
		HttpURLConnection conn = (HttpURLConnection) postUrl.openConnection();
		// Output to the conn. Default is
		// false, set to true because post
		// method must write something to the
		// conn
		// 设置是否向connection输出,因为这个是post请求,参数要放在
		// http正文内,因此需要设为true
		conn.setDoOutput(true);
		// Read from the conn. Default is true.
		conn.setDoInput(true);
		conn.setConnectTimeout(5 * 1000);
		conn.setRequestProperty("Authorization",
				"Bearer 66dc31e3f85a34a0349495abe90e9de0");
		// Set the post method. Default is GET
		conn.setRequestMethod(method);
		// Post cannot use caches
		// Post 请求不能使用缓存
		conn.setUseCaches(false);
		// This method takes effects to
		// every instances of this class.
		// URLConnection.setFollowRedirects是static函数,作用于所有的URLConnection对象。
		// conn.setFollowRedirects(true);

		// This methods only
		// takes effacts to this
		// instance.
		// URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数
		conn.setInstanceFollowRedirects(true);
		// Set the content type to urlencoded,
		// because we will write
		// some URL-encoded content to the
		// conn. Settings above must be set before connect!
		// 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
		// 意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode
		// 进行编码

		conn.setRequestProperty("Content-Type",
				"application/x-www-form-urlencoded");

		// 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
		// 要注意的是connection.getOutputStream会隐含的进行connect。
		conn.connect();
		OutputStream out = conn.getOutputStream();
		// The URL-encoded contend
		// 正文,正文内容其实跟get的URL中'?'后的参数字符串一致
		StringBuilder sb = new StringBuilder();
		if (null != params) {
			int i = params.size();
			for (Map.Entry<String, String> entry : params.entrySet()) {
				if (i == 1) {
					sb.append(entry.getKey() + "=" + entry.getValue());
				} else {
					sb.append(entry.getKey() + "=" + entry.getValue() + "&");
				}

				i--;
			}
		}
		String content = sb.toString();
		System.out.print(content);
		// DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面
		out.write(content.getBytes("UTF-8"));
		out.flush();
		out.close(); // flush and close
		InputStream inStream = conn.getInputStream();
		String result = inputStream2String(inStream);
		System.out.println(result);
		conn.disconnect();
	}

	/**
	 * 豆瓣必须严格限制get请求所以增加这个方法 这个方法也可以自定义请求
	 * 
	 * @param url
	 * @param method
	 * @throws Exception
	 */

	public static void customrequestget(String url,
			HashMap<String, String> map, String method) throws Exception {
		if (null != map) {
			int i = 0;
			for (Map.Entry<String, String> entry : map.entrySet()) {

				if (i == 0) {
					url = url + "?" + entry.getKey() + "=" + entry.getValue();
				} else {
					url = url + "&" + entry.getKey() + "=" + entry.getValue();
				}

				i++;
			}
		}
		URL murl = new URL(url);
		System.out.print(url);
		HttpURLConnection conn = (HttpURLConnection) murl.openConnection();
		conn.setConnectTimeout(5 * 1000);
		conn.setRequestMethod(method);
		conn.setRequestProperty("Authorization",
				"Bearer 66dc31e3f85a34a0349495abe90e9de0");
		InputStream inStream = conn.getInputStream();

		String result = inputStream2String(inStream);
		System.out.println(result);
		conn.disconnect();
	}

	public static String inputStream2String(InputStream in) throws IOException {
		StringBuffer out = new StringBuffer();
		byte[] b = new byte[4096];
		for (int n; (n = in.read(b)) != -1;) {
			out.append(new String(b, 0, n));
		}
		return out.toString();
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值