java实现调用https请求的简易代码(学习笔记)
- 简单的实现java执行网页请求
- 并将网页内容按字符串格式返回
直接上代码:
public static String https(String Url_Path) {
//初始化
InputStream inputStream = null;
HttpURLConnection httpURLConnection = null;
StringBuilder receivedContent = null;
try {
URL url = new URL(Url_Path);
if (url != null) {
httpURLConnection = (HttpURLConnection) url.openConnection();
// 设置连接网络的超时时间
httpURLConnection.setConnectTimeout(2000);
httpURLConnection.setDoInput(true);
// 设置https请求使用POST方式请求
httpURLConnection.setRequestMethod("POST");
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == 200) {
// 获得一个输入流
inputStream = httpURLConnection.getInputStream();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"));
receivedContent = new StringBuilder(1024);
String line = "";
while((line = reader.readLine()) != null) {
receivedContent.append(line);
}
reader.close();
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (receivedContent==null){
return "";
}
return receivedContent.toString();
}
public static void main(String[] args) {
String message = https("https://www.baidu.com");
System.out.println(message);
}
打印输出内容如下,说明执行www.baidu.com网页请求成功。
谢谢阅读,感谢支持!如有错误,请多多指教!!