package wjb.baidu.ai.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * http 工具类
 */
public class HttpUtil {

	public static String post(String requestUrl, String accessToken, String params) throws Exception {
		String contentType = "application/x-www-form-urlencoded";
		return HttpUtil.post(requestUrl, accessToken, contentType, params);
	}

	public static String post(String requestUrl, String accessToken, String contentType, String params) throws Exception {
		String encoding = "UTF-8";
		if (requestUrl.contains("nlp")) {
			encoding = "GBK";
		}
		return HttpUtil.post(requestUrl, accessToken, contentType, params, encoding);
	}

	public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding) throws Exception {
		String url = requestUrl + "?access_token=" + accessToken;
		return HttpUtil.postGeneralUrl(url, contentType, params, encoding);
	}

	public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding) throws Exception {
		URL url = new URL(generalUrl);
		// 打开和URL之间的连接
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod("POST");
		// 设置通用的请求属性
		connection.setRequestProperty("Content-Type", contentType);
		connection.setRequestProperty("Connection", "Keep-Alive");
		connection.setUseCaches(false);
		connection.setDoOutput(true);
		connection.setDoInput(true);

		// 得到请求的输出流对象
		DataOutputStream out = new DataOutputStream(connection.getOutputStream());
		out.write(params.getBytes(encoding));
		out.flush();
		out.close();

		// 建立实际的连接
		connection.connect();
		// 定义 BufferedReader输入流来读取URL的响应
		BufferedReader in = null;
		in = new BufferedReader(new InputStreamReader(connection.getInputStream(), encoding));
		String result = "";
		String getLine;
		while ((getLine = in.readLine()) != null) {
			result += getLine;
		}
		in.close();
		return result;
	}
}
最近下载更多
coolcool123  LV1 3月17日
lironggang  LV38 2023年4月27日
97622282  LV1 2022年6月7日
王伟杰  LV2 2021年11月12日
淮竹  LV1 2021年10月13日
我是桃子呀  LV3 2021年7月14日
jokerYao  LV1 2020年11月27日
cas  LV9 2020年9月21日
sakura_fc  LV1 2020年9月10日
wanhaiq  LV3 2020年7月2日
最近浏览更多
coolcool123  LV1 3月17日
liyonggang  LV2 1月19日
miaoshi  LV16 1月3日
837055744 2023年7月20日
暂无贡献等级
2017143155  LV12 2023年6月27日
lironggang  LV38 2023年4月27日
nsq0006  LV6 2023年3月3日
lc4519  LV3 2023年3月3日
uni-code_0123  LV1 2023年1月10日
arkic1 2022年12月1日
暂无贡献等级
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友