一. 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
三.连接步骤
-
创建一个URL对象:
URL url=new URL(“接口地址”)
-
调用URL对象的openConnection()来获取HttpURLConnection对象实例;
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
- 设置HTTP请求使用的方法:GET、POST或其他请求;
connection.setRequestMethod(“GET”);
- 设置连接超时,读取超时的毫秒数,以及服务器希望得到的一些消息头;
connection.setConnectTimeout(6*1000);
connection.setReadTimeout(6 * 1000);
- 调用getInputStream()或getOutputStream()方法获得服务器返回的输入流和输出流,进行操作。
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
- 最后调用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;
}