Java提交Http Get和Post请求的通用方法

以往我们提交Http Get请求和Post请求时,一般会根据请求方式分别编写方法进行调用,以下方法则将两种请求的调用方式进行了整合,这样以后调用请求的时候就不需要考虑请求方式是Get还是Post,通通只要调用此方法就行了。代码如下:

public static ServiceResult sendRequest(String url, String obj, Map<String, String> headers, RequestMethod requestMethod, ContentType contentType) throws IOException {
    //返回对象,包含businessObject(返回数据)、success(是否成功返回)、
    //message(返回信息,一般是错误信息)、responseCode(返回码)等属性
	ServiceResult result = new ServiceResult();
        //Get提交时直接在url中拼接参数,obj是已经拼接好的参数字符串
	if (requestMethod.toString().equals("GET") && obj.length() > 0) {
		url = url + "?" + obj;
	}
	URL requestUrl = new URL(url);
	HttpURLConnection connection=null;
	StringBuffer sbBuffer = null;
	try {
        //打开连接,设置连接参数
		connection = (HttpURLConnection) requestUrl.openConnection();
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setRequestMethod(requestMethod.toString());
        //设置内容类型,默认为json
		if (contentType == null) {
			connection.setRequestProperty("Content-Type", "application/json");
		} else {
			connection.setRequestProperty("Content-Type",contentType);
		}
		connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");
		connection.setRequestProperty("Accept", "*/*");
        //设置请求头,请求头信息存在map中,因此需要循环遍历出来进行设置
		if (headers != null) {
			for (Iterator iter = headers.keySet().iterator(); iter.hasNext();){
				String name = (String) iter.next();
				String value = String.valueOf(headers.get(name));
				connection.setRequestProperty(name, value);
			}
		}
		connection.setReadTimeout(2000000);
		connection.setConnectTimeout(2000000);
		connection.connect();
        //如果是post请求,则需要将参数写入到输出流中
		OutputStream outputStream = connection.getOutputStream();
		outputStream.write(obj.toString().getBytes());
		outputStream.flush();
		outputStream.close();
        //获取返回结果码
		int code = connection.getResponseCode();
		if (code == 200) {//返回成功的结果码
            //从输入流中读取返回信息
			InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream());
			BufferedReader reader = new BufferedReader(inputStreamReader);
			sbBuffer = new StringBuffer("");
			String lines;
			while ((lines = reader.readLine()) != null) {
				lines = new String(lines.getBytes(), "utf-8");
				sbBuffer.append(lines);
			}
			reader.close();
            inputStreamReader.close();
            //将返回信息设置到返回对象中
			result.setResponseCode(200);
			result.setIsSuccess(true);
			result.setBusinessObject(sbBuffer.toString());
		} else {//返回失败
            //将返回失败信息设置到返回对象中
			result.setBusinessObject(connection.getResponseMessage());
			result.setMessage(connection.getResponseMessage());
			result.setResponseCode(connection.getResponseCode());
			result.setIsSuccess(false);
		}
        //断开连接
		connection.disconnect();
	} catch (IOException e) {
		e.printStackTrace();
        //将异常信息设置到返回对象中
		result.setIsSuccess(false);
		result.setMessage(e.getMessage());
		result.setResponseCode(0);
	}
	return result;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wunianisme

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值