java url linux_使用Java内置类HttpUrlConnection实现HTTP请求

1. 概述

在这篇快速教程中,我们将使用Java内置类HttpUrlConnection来实现一个Http请求。

2. HttpUrlConnection

HttpUrlConnection类允许我们不用添加其他任何类库就能实现基本的Http请求。所有需要的类都包含在 java.net包内。缺点是,相比于其他http类库,该方法有点笨重,而且也没有提供一些高级特性的API,比如添加请求头,添加认证等。不过这些都不要紧。你完全可以将这个实现封装一下,添加一些高级特性也不是很复杂。

如果你只是想快速地进行些Http请求而不想添加一些类库的话,本文的这些代码就足够了。

另外,如果你对java的http请求基本实现不很了解,本文给出的代码也会有些帮助。

3. 创建请求

HttpUrlConnection类的创建是通过URL 类的openConnection()方法。这个方法只是创建一个连接对象,并不建立连接。

通过设置requestMethod属性,HttpUrlConnection类可以创建各种请求类型——包括GET, POST, HEAD, OPTIONS, PUT, DELETE, TRACE。

比如创建一个GET请求:

URL url = new URL("www.linuxidc.com");

HttpURLConnection con = (HttpURLConnection) url.openConnection();

con.setRequestMethod("GET");

4. 添加请求参数

如果我们想要添加请求参数,我们需要设置doOutput 为true,然后将请求参数拼接成字符串,格式param1=value&param2=value,以流的形式写入到HttpUrlConnection 实例的OutputStream中。示例代码如下:

Map parameters = new HashMap<>();

parameters.put("param1", "val");

con.setDoOutput(true);

DataOutputStream out = new DataOutputStream(con.getOutputStream());

out.writeBytes(ParameterStringBuilder.getParamsString(parameters));

out.flush();

out.close();

为方便转换字符串参数,我写了个工具类ParameterStringBuilder。类中包含一个静态方法getParamsString()将Map转换成对应格式的字符串:

public class ParameterStringBuilder {

public static String getParamsString(Map params)

throws UnsupportedEncodingException{

StringBuilder result = new StringBuilder();

for (Map.Entry entry : params.entrySet()) {

result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));

result.append("=");

result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));

result.append("&");

}

String resultString = result.toString();

return resultString.length() > 0

? resultString.substring(0, resultString.length() - 1)

: resultString;

}

}

5. 添加请求头

通过setRequestProperty() 方法可以添加请求头:

con.setRequestProperty("Content-Type", "application/json");

通过getHeaderField()方法可以读取响应头:

String contentType = con.getHeaderField("Content-Type");

6. 配置超时时间

类允许我们设置连接超时时间和读取超时时间。这些值决定了连接建立的最大等待时间间隔或读取到达数据的最大等待时间间隔。

设置超时时间,我们可以调用方法setConnectTimeout() 和方法setReadTimeout():

con.setConnectTimeout(5000);

con.setReadTimeout(5000);

这个例子中我们将超时时间设为5秒。

7.  处理Cookies

java.net 包包含的类CookieManager,HttpCookie等能很便捷地处理Cookies.

首先,从响应中读取cookies,我们先获取相应头里的Set-Cookie值,然后解析成HttpCookie对象的List.

String cookiesHeader = con.getHeaderField("Set-Cookie");

List cookies = HttpCookie.parse(cookiesHeader);

接下来,我们将cookies存储起来:

cookies.forEach(cookie -> cookieManager.getCookieStore().add(null, cookie));

我们检查cookies中是否包含一个username属性,如果不包含,我们把一个叫zhangsan的username添加进去:

Optional usernameCookie = cookies.stream()

.findAny().filter(cookie -> cookie.getName().equals("username"));

if (usernameCookie == null) {

cookieManager.getCookieStore().add(null, new HttpCookie("username", "john"));

}

最后,将cookies添加到请求中去,我们需要在关闭连接和重新打开连接后,添加Cookie请求头 :

con.disconnect();

con = (HttpURLConnection) url.openConnection();

con.setRequestProperty("Cookie",

StringUtils.join(cookieManager.getCookieStore().getCookies(), ";"));

8. 处理重定向

我们可以通过调用方法setInstanceFollowRedirects(),设置为true或者false,来控制是否允许一个特定连接自动跟随重定向:

con.setInstanceFollowRedirects(false);

也可以全局设置所有的连接是否允许自动跟随重定向:

HttpUrlConnection.setFollowRedirects(false);

默认是允许自动跟随重定向的。

请求返回状态码301,302表示重定向,我们可以获取响应头的Location属性并用新的URL创建一个新的连接。

if (status == HttpURLConnection.HTTP_MOVED_TEMP

|| status == HttpURLConnection.HTTP_MOVED_PERM) {

String location = con.getHeaderField("Location");

URL newUrl = new URL(location);

con = (HttpURLConnection) newUrl.openConnection();

}

9. 读取响应

通过读取HttpUrlConnection实例的InputStream流来读取响应。

读取响应常用方法有getResponseCode(), connect(), getInputStream() or getOutputStream() 。

比如,读取响应状态码:

int status = con.getResponseCode();

比如,读取响应头:

String contentType = con.getHeaderField("Content-Type");

比如,读取响应文本:

BufferedReader in = new BufferedReader(

new InputStreamReader(con.getInputStream()));

String inputLine;

StringBuffer content = new StringBuffer();

while ((inputLine = in.readLine()) != null) {

content.append(inputLine);

}

in.close();

关闭连接:

con.disconnect();

结论

在这篇文章中,我们展示了如何通过HttpUrlConnection类来时间Http请求。以下代码可以直接拷贝使用。由于太简单,就不传github了。

package com.linuxidc.utils;

import java.io.*;

import java.net.HttpURLConnection;

import java.net.URL;

import java.net.URLEncoder;

import java.util.HashMap;

import java.util.Map;

public class HttpUtil {

private static String POST = "POST";

private static String GET = "GET";

private static String CONTENT_TYPE_URLENCODED = "application/x-www-form-urlencoded";

private static String CONTENT_TYPE_JSON = "application/json";

private static String httpRequest(String method, String contentType, String urlStr, HashMap paras)

throws IOException {

URL url = new URL(urlStr);

HttpURLConnection con = (HttpURLConnection) url.openConnection();

con.setConnectTimeout(5000);

con.setReadTimeout(5000);

con.setRequestMethod("POST");

con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

if(paras != null && !paras.isEmpty()){

con.setDoOutput(true);

DataOutputStream out = new DataOutputStream(con.getOutputStream());

out.writeBytes(ParameterStringBuilder.getParamsString(paras));

out.flush();

out.close();

}

BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

String inputLine;

StringBuffer content = new StringBuffer();

while ((inputLine = in.readLine()) != null) {

content.append(inputLine);

}

in.close();

con.disconnect();

return content.toString();

}

private static class ParameterStringBuilder {

public static String getParamsString(Map params)

throws UnsupportedEncodingException {

StringBuilder result = new StringBuilder();

for (Map.Entry entry : params.entrySet()) {

result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));

result.append("=");

result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));

result.append("&");

}

String resultString = result.toString();

return resultString.length() > 0

? resultString.substring(0, resultString.length() - 1)

: resultString;

}

}

public static String httpGetRequest(String url){

try {

return httpRequest(GET, CONTENT_TYPE_URLENCODED, url, null);

} catch (IOException e) {

e.printStackTrace();

}

return "";

}

public static String httpPostRequest(String url, HashMap paras){

try {

return httpRequest(POST, CONTENT_TYPE_URLENCODED, url, paras);

} catch (IOException e) {

e.printStackTrace();

}

return "";

}

}

0b1331709591d260c1c78e86d0c51c18.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值