【JAVA基础】HttpURLConnection详解

一. HTTPURLConnection详解

​ HttpURLConnection类是位于java.net包下继承了URLConnection类的一个抽象类,每个 HttpURLConnection 实例都用于发出单个请求,包括了常见的几乎所有的请求类型。

​ 在HttpURLConnection类的定义当中提供了一个必填的参数,是一个URL类型的参数,第二部分将会对这一个类型进行详细讲解。HttpURLConnection对象不能直接构造,需使用URL类中的openConnection()方法来创建实例。

​ HttpURLConnection类拥有多个不同的子类,用于处理不同的应用场景,IDEA中显示的子类如下所示:

在这里插入图片描述
​ 其中,HttpsURLConnection类常用于建立Https连接。

二. URL详解

​ HttpURLConnection的使用需要依赖于URL类。

​ URL类同样位于java.net包下,是一个Object类派生出来的final类,不允许派生出其他子类,提供了多种构造方法。

public URL(String url) throws MalformedURLeException
public URL(String protocol ,String hostname, String file)throws MalformedURLeException
public URL(String protocol, String host, int port ,String file)throws MalformedURLeException
public URL(URL base, String relative)throws MalformedURLeException

​ 通过结合HttpConnection的使用可以简单的建立起网络连接,罗列了这个过程当中经常使用的方法:

public URLConnection openConnection() throws java.io.IOException
public final InputStream openStream() throws java.io.IOException

三.连接步骤

  1. 创建一个URL对象:

    URL url=new URL(“接口地址”)
    
  2. 调用URL对象的openConnection()来获取HttpURLConnection对象实例;

	HttpURLConnection connection= (HttpURLConnection) url.openConnection();
  1. 设置HTTP请求使用的方法:GET、POST或其他请求;
	connection.setRequestMethod(GET);
  1. 设置连接超时,读取超时的毫秒数,以及服务器希望得到的一些消息头;
	connection.setConnectTimeout(6*1000);
	connection.setReadTimeout(6 * 1000);
  1. 调用getInputStream()或getOutputStream()方法获得服务器返回的输入流和输出流,进行操作。
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  1. 最后调用disconnect()方法将HTTP连接关掉,并将输入输出流关闭;
		connection.disconnect();
		in.close();

四.代码示例

public String testInterface(Map<String, Object> param) throws IOException {
        String result = null;
        Map<String, Object> interfaceMap = (Map<String, Object>) param.get("interface");
        String requestMethod = interfaceMap.get("requestMethod").toString();
        String url = interfaceMap.get("url").toString();
        List<Map> multipleSelectionHeader = (List<Map>) interfaceMap.get("multipleSelectionHeader");
        List<Map> multipleSelectionParam = (List<Map>) interfaceMap.get("multipleSelectionParam");
        if (requestMethod.equals("GET")) {
            StringBuilder urlBuilder = new StringBuilder(url);
            for (int i = 0; i < multipleSelectionParam.size(); i++) {
                if (i == 0) {
                    urlBuilder.append("?" + multipleSelectionParam.get(i).get("key").toString() + "=" + URLEncoder.encode(multipleSelectionParam.get(i).get("value").toString(),"UTF-8"));
                } else {
                    urlBuilder.append("&" + multipleSelectionParam.get(i).get("key").toString() + "=" + URLEncoder.encode(multipleSelectionParam.get(i).get("value").toString(),"UTF-8"));
                }
            }
            URL urlStr = new URL(urlBuilder.toString());
            HttpURLConnection con = (HttpURLConnection) urlStr.openConnection();
            con.setRequestMethod(requestMethod);
            for (int j = 0; j < multipleSelectionHeader.size(); j++) {
                con.setRequestProperty(multipleSelectionHeader.get(j).get("key").toString(), multipleSelectionHeader.get(j).get("value").toString());
            }
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer content = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }
            in.close();
            result = content.toString();
        } else if (requestMethod.equals("POST")) {
            String requestBody = "";
            if (multipleSelectionParam.size() > 0) {
                for (int i = 0; i < multipleSelectionParam.size(); i++) {
                    if (i == 0) {
                        requestBody+=("{\"" + multipleSelectionParam.get(i).get("key").toString() + "\":\"" + multipleSelectionParam.get(i).get("value").toString()+"\"");
                    }else{
                        requestBody+=(",\""+multipleSelectionParam.get(i).get("key").toString() + "\":\"" + multipleSelectionParam.get(i).get("value").toString()+"\"");
                    }
                }
                requestBody+="}";
            } else {
                requestBody = "{}";
            }
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod(requestMethod);
            for (int j = 0; j < multipleSelectionHeader.size(); j++) {
                con.setRequestProperty(multipleSelectionHeader.get(j).get("key").toString(), multipleSelectionHeader.get(j).get("value").toString());
            }
            con.setDoOutput(true);
            OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
            out.write(requestBody);
            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();
            result = content.toString();
        }
        return result;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

卑微的小红猪

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

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

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

打赏作者

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

抵扣说明:

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

余额充值