HttpURLConnection模拟Http操作 并自定义http请求
博客专区 > SuShine 的博客 > 博客详情
HttpURLConnection模拟Http操作 并自定义http请求
SuShine 发表于2年前
HttpURLConnection模拟Http操作 并自定义http请求
  • 发表于 2年前
  • 阅读 7
  • 收藏 0
  • 点赞 0
  • 评论 0

华为云·免费上云实践>>>   

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();
	}
}

共有 人打赏支持
粉丝 118
博文 312
码字总数 79453
×
SuShine
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: