Java中如何发送Http请求呢?
下文笔者讲述java代码中发送Http请求的方法及示例分享
学习完本篇之后,你将彻底掌握发送http请求的方法,如下所示
学习完本篇之后,你将彻底掌握发送http请求的方法,如下所示
实现思路: 借助java.net.HttpUrlConnection对象 进行连接远程URL地址 然后传入相应的参数信息 获取返回信息 使用java原生代码,即可实现http请求例:Java实现Http请求的示例
public static String executePost(String targetURL, String urlParameters) {
HttpURLConnection connection = null;
try {
//Create connection
URL url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length",
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


