HTTP两种请求方式对比

本文通过实际案例对比了两种不同的HTTP POST请求方法在API接口测试中的表现,一种使用了Apache HttpClient库,另一种使用了Java标准库的HttpURLConnection。在本地测试环境下,两种方法都能正常工作,但在正式环境中,后者出现了错误。通过对请求头信息的分析,发现兼容性问题可能是导致差异的原因。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天在进行API接口测试的时候遇到个比较奇怪的事情,两个方法都是执行http请求,但是返回的结果有一个却是报错的,url在本地测试的时候两种方式却都是可以的,url切换到正式环境的第二种却是报错,我猜是因为有一些请求头信息没有传递过去,所以导致的错误,以此记录下,说明了请求方式1是兼容性比较好的
在这里插入图片描述
代码如下:

import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class Test {
	public static void main(String[] args) {
		String url = "http://xxx/api/xxx.do";
			try {
				//传参
				JSONObject object = new JSONObject();
				object.put("day", "2020-02-20");
				String str = httpJson(url, object.toString());
				System.out.println("请求方式1:"+str);
				String result = Request.Post(url).bodyString(object.toString(),
						ContentType.APPLICATION_JSON).execute().returnContent().asString();
				System.out.println("请求方式2:"+result);

			} catch (Exception e) {
				e.printStackTrace();
			}
	}

	public static String httpJson(String url, String json) throws IOException {
		HttpURLConnection conn = null;
		OutputStream out = null;
		InputStream in = null;
		//转换为字节数组
		byte[] param = json.getBytes();
		String result = "";
		try {
			// 建立http连接
			conn = getHttpURLConnection(url);
			// 设置允许输出
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 设置不用缓存
			conn.setUseCaches(false);
			// 设置传递方式
			conn.setRequestMethod("POST");
			// 设置维持长连接
			conn.setRequestProperty("Connection", "Keep-Alive");
			// 设置文件长度
			conn.setRequestProperty("Content-Length", String.valueOf(param.length));
			// 设置请求信息类型:
			conn.setRequestProperty("Content-type", "application/json;charset=utf-8");
			// 设置客户端接受信息类型
			conn.setRequestProperty("Accept", "application/json");
			// 开始连接请求
			conn.connect();
			// 获取连接输出流
			out = conn.getOutputStream();
			// 写入请求的字符串
			out.write(param);
			out.flush();
			// 请求返回的状态
			if (conn.getResponseCode() == 200) {
				// 请求返回的数据
				in = conn.getInputStream();
				byte[] data = new byte[in.available()];
				in.read(data);
				result = new String(data);
			}
		} finally {
			close(conn, out, in);
		}
		return result;
	}

	public static HttpURLConnection getHttpURLConnection(String url) throws IOException{
		return (HttpURLConnection) new URL(url).openConnection();
	}
	
	private static void close(HttpURLConnection conn , OutputStream out, InputStream in) {
		try {
			if(conn != null){
				conn.disconnect();
			}
			if(out != null){
				out.close();
			}
			if(in != null){
				in.close();
			}
		} catch (Exception e) {

		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值