HttpClient与HttpUrlConnection进行跨域请求

本文对比了HttpClient和HttpUrlConnection在Java后端进行跨域请求时的使用,包括它们的简介、特点、用法和区别。HttpClient功能更丰富,适合处理复杂的请求,而HttpURLConnection则更简洁,适用于大部分基础请求。性能上,HttpURLConnection在速度和缓存上有优势。Android推荐使用HttpURLConnection,但在旧版本中存在一些问题。
摘要由CSDN通过智能技术生成

HttpClient与HttpUrlConnection 在java后端进行跨域请求,访问调用服务的时候用得比较多。都是基于http的请求,进行访问

 

一. HttpURLConnection简介

在JDK的java.net包中已经提供了访问HTTP协议的基本功能的类:HttpURLConnection。

HttpURLConnection是Java的标准类,它继承自URLConnection,可用于向指定网站发送GET请求、POST请求。它在URLConnection的基础上提供了如下便捷的方法:

int getResponseCode(); // 获取服务器的响应代码。
String getResponseMessage(); // 获取服务器的响应消息。
String getResponseMethod(); // 获取发送请求的方法。
void setRequestMethod(String method); // 设置发送请求的方法

下面是HttpURLConnection的GET请求与POST请求的演示

get请求

public static String  doGet(String urlStr) {
		try {
			URL url=new URL(urlStr);
			HttpURLConnection connection=(HttpURLConnection) url.openConnection();
			//设置请求参数(过期时间,输入、输出流、访问方式),以流的形式进行连接 
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setUseCaches(false);//设置缓存
			connection.setConnectTimeout(20000);//设置超时时间 毫秒
			 connection.setInstanceFollowRedirects(true);//设否执行http重定向
			 
			 //建立连接
			 connection.connect();
			 String msg="";
			 int code =connection.getResponseCode();
			 if(code==200) {
				 BufferedReader br=new BufferedReader(new InputStreamReader(connection.getInputStream()));
				 String line=null;
				 while(((line=br.readLine())!=null)) {
					 msg+=line+"\n";
				 }
				 br.close();
			 }
			 //关闭链接
			 connection.disconnect();
			 //输出结果
			 System.out.println(msg);
			 return msg;
		} catch (Exception e) {
			// TODO: handle exception
			return null;
		}
		
	}

post请求

public static String doPost(Map<String,String> params,String urlStr,String encode) {
		if(encode==null) {
			encode="utf-8";
		}
		try {
			URL url=new URL(urlStr);
			HttpURLConnection conn=(HttpURLConnection) url.openConnection();
			co
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值