java发起http请求工具包

java发起http请求工具包

通过java发起http请求,拉取数据

使用到的jar:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

工具方法:

public class HttpRequest {

	private static final Logger logger = LoggerFactory.getLogger(HttpRequest.class);
	
	/**
	 *处理Https GET|POST 请求
	 * @param requestUrl 请求地址
	 * @param requestMethod 请求方法(GET|POST)
	 * @param outputStr 
	 * @date 2017年3月31日 上午10:35:32
	 */
	public static String httpRequest(String httpUrl, String requestMethod,String outputStr) {
		StringBuffer buffer = new StringBuffer();
		try {
			URL url = new URL(httpUrl);
			URLConnection rulConnection = url.openConnection();
			HttpURLConnection httpUrlConnection = (HttpURLConnection) rulConnection;
			httpUrlConnection.setDoOutput(true);
			httpUrlConnection.setDoInput(true);
			httpUrlConnection.setUseCaches(false);
			httpUrlConnection.setRequestProperty("Content-Type",
					"application/json");
			httpUrlConnection
					.setRequestProperty("POST", "/violations HTTP/1.1");
			httpUrlConnection.setRequestMethod(requestMethod);
			httpUrlConnection.connect();
			
			if (null != outputStr) {
				OutputStream outputStream = httpUrlConnection.getOutputStream();
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}
			InputStream inputStream = httpUrlConnection.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(
					inputStream, "UTF-8");
			BufferedReader bufferedReader = new BufferedReader(
					inputStreamReader);
			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			inputStream = null;
			httpUrlConnection.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return buffer.toString();
	}
}

调用方法:

String jsonString = HttpRequest.httpRequest(urlIn, “POST”, object.toString());

返回的是json格式字符串,通过解析结果串得到反馈结果。。。。。

[https://editor.csdn.net/md?not_checkout=1&articleId=121426949]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值