Java HttpURLConnction和HttpClient

(1)HttpURLConnction

HttpURLConnection是java的标准类,HttpURLConnection继承自URLConnection,可用于向指定网站发送GET请求、POST请求。

String urls = "xxx";
URL url = new URL(urls);
		  // 此处的urlConnection对象实际上是根据URL的 
          // 请求协议(此处是http)生成的URLConnection类 
          // 的子类HttpURLConnection,故此处最好将其转化 	
          // 为HttpURLConnection类型的对象,以便用到 
          // HttpURLConnection更多的API
HttpURLConnction conn = (HttpURLConnection) urls.openConnection();
//HttpURLConnection对象参数问题
conn.setRequestMethod("GET");//选择请求类型:“GET”或者“POST”。
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");//post的传递的是json类型

//HttpURLConnection连接问题
// 此处getOutputStream会隐含的进行connect(即:如同调用上面的connect()方法, 
// 所以在开发中不调用上述的connect()也可以)。 
OutputStream outStrm = conn.getOutputStream(); //GET时不需要这个  
//POST时通过流输出
DataOutputStream w = new DataOutputStream(conn.getOutputStream());
w.writeBytes(param);
w.close();
//流关闭后,调用getInputStream.返回一个输入流
BufferedReader in = new BufferedReader(
					new InputStreamReader(conn.getInputStream(), "utf-8"));//GET从这里获得返回结果
in.close();




(2) HttpClient

GET有参(URL传递)

public void DoGet() {
		// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		// 参数
		StringBuffer params = new StringBuffer();
		// 创建Get请求
		HttpGet httpGet = new HttpGet("http://localhost:12345/doGetControllerTwo" + "?" + params);
		// 响应模型
		CloseableHttpResponse response = null;
		try {
			// 配置信息
			RequestConfig requestConfig = RequestConfig.custom()
					// 设置连接超时时间(单位毫秒)
					.setConnectTimeout(5000)
					// 设置请求超时时间(单位毫秒)
					.setConnectionRequestTimeout(5000)
					// socket读写超时时间(单位毫秒)
					.setSocketTimeout(5000)
					// 设置是否允许重定向(默认为true)
					.setRedirectsEnabled(true).build();
 
			// 将上面的配置信息 运用到这个Get请求里
			httpGet.setConfig(requestConfig);
 
			// 由客户端执行(发送)Get请求
			response = httpClient.execute(httpGet);
 
			// 从响应模型中获取响应实体
			HttpEntity responseEntity = response.getEntity();
			System.out.println("响应状态为:" + response.getStatusLine());
			if (responseEntity != null) {
				System.out.println("响应内容长度为:" + responseEntity.getContentLength());
				System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				// 释放资源
				if (httpClient != null) {
					httpClient.close();
				}
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
}

POST

public void doPost(){
		// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();

		//参数转化为json字符串
		String entityString=JSON.toJSONString(map);
		HttpPost httpPost = new HttpPost();
		httpPost.setEntity(new StringEntity(entityString, Charset.forName("utf-8")));

		//设置配置到post
		RequestConfig requestConfig = RequestConfig.custom()
			.setSocketTimeout(20000)
			.setConnectTimeout(20000)
			.build();//设置请求和传输超时时间
		httpPost .setConfig(requestConfig);
	
		// 响应模型
		CloseableHttpResponse response = null;
		try {
			// 由客户端执行(发送)Post请求
			response = httpClient.execute(httpPost);
			// 从响应模型中获取响应实体
			HttpEntity responseEntity = response.getEntity();
			System.out.println("响应状态为:" + response.getStatusLine());
			int status=response.getStatusLine().getStatusCode();
					//获取返回的状态码,只有状态成功的话记录相关返回的结果信息
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				// 释放资源
				if (httpClient != null) {
					httpClient.close();
				}
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值