1 需求
2 接口
Class HttpURLConnection
java.lang.Object? ????????java.net.URLConnection? ????????????????java.net.HttpURLConnection?
public abstract class HttpURLConnection extends URLConnection
Field Detail
Constructor Detail
- protected HttpURLConnection(URL u)
Method Detail
- public void setRequestMethod(String method) throws ProtocolException
- public int getResponseCode() throws IOException
Class URLConnection
java.lang.Object? ????????java.net.URLConnection
public abstract class URLConnection extends Object
Field Detail
Constructor Detail
Method Detail
- public InputStream getInputStream() throws IOException
?
Class URL
java.lang.Object? ????????java.net.URL
public final class URL extends Object implements Serializable
Constructor Detail
- public URL(String spec) throws MalformedURLException
Method Detail
- public URLConnection openConnection() throws IOException
- public URLConnection openConnection(Proxy proxy) throws IOException
3 示例
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* 第一步,创建远程连接
* 第二步,设置连接方式(get、post、put。。。)
* 第三步,设置连接超时时间
* 第四步,设置响应读取时间
* 第五步,发起请求
* 第六步,获取请求数据
* 第七步,关闭连接
*/
public class Test {
public static void main(String[] args) {
StringBuffer result = new StringBuffer();
try {
// 创建连接
URL url = new URL("http://www.dvwa.com/login.php");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方式
connection.setRequestMethod("GET");
// 设置连接超时时间
connection.setReadTimeout(15000);
// 开始连接
connection.connect();
// 获取请求数据
if (connection.getResponseCode() == 200) {
InputStream is = connection.getInputStream();
if (is != null) {
InputStreamReader ir = new InputStreamReader(is, "UTF-8");
BufferedReader br = new BufferedReader(ir);
String line = null;
while ((line = br.readLine()) != null) {
result.append(line);
}
}
}
//
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(result);
}
}
4 参考资料
java实现调用http请求的几种常见方式_qq_duhai的博客-CSDN博客_java http
?
|