HttpURLConnection大白话讲解(史上最全)
下文笔者采用大白话的方式讲述HttpURLConnection的见解
HttpURLConnection个人见解
HttpURLConnection是一个抽象类 她定义了一套操作url链接的方法 我们通常使用url.openConnection()方法创建HttpURLConnection实例
获得HttpURLConnection对象的示例
//使用 POST 方法
URL url = new
URL("http://ip.taobao.com//service/getIpInfo.php");
//使用 GET 方法
//URL url = new URL("http://ip.taobao.com/service/getIpInfo.php?ip=xxx.xxx.xxx.xxx");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//设置请求属性
//设置连接超时时间
connection.setConnectTimeOut(10000);
//设置读取超时时间
connection.setReadTimeOut(10000);
//设置请求参数
connection.setRequestMethod("POST");
//添加HTTP HEAD参数
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.7 Safari/537.36");
//设置是否向 httpUrlConnection 输出,
//对于post请求,参数要放在 http 正文内,因此需要设为true
//默认情况下是false;
connection.setDoOutput(true);
//设置是否从httpUrlConnection读入,默认情况下是true
connection.setDoInput(true);
这些属性的设置必须在connect()方法之前完成
setDoOutput()方法:为getOutputStream()服务
setDoInput()方法:为getInputStream()服务
//调用connect()连接远程信息
connection.connect();
//使用getOutputStream()向服务端传输POST 消息
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
writer.write("ip=xxx.xxx.xxx.xxx");
writer.flush();
writer.close();
//HttpURLConnection其它方法
public String getContentType()
public int getContentLength()
public String getContentEncoding()
public long getDate()
public long getExpiration()
public long getLastModified()
//关闭 HttpURLConnection
connection.disconnect();
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


