HttpURLConnection的一些用法

HttpURLConnection:         也是一个抽象类, 这是一个继承URLConnection的子类,一些方法在URLConnection中已经熟悉。
    相关常量:
         HTTP_OK 连接成功 值为200
         HTTP_INTERNAL_ERROR 服务器内部错误 500
    相关方法:
         |--disConnect(): 断开链接
         |--getResponceCode(): 得到响应状态码
代码示意:
  
  
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
 
public class HttpURLConnectionDemo01 {
public static void main(String[] args) throws Exception {
String spec = "https://ss0.baidu.com/7Po3dSag_xI4khGko9WTAnF6hhy/news/q=100/sign=643ba8b7d20735fa97f04ab9ae500f9f/8ad4b31c8701a18b48f518e3982f07082838fe04.jpg";
//确定资源的位置
URL url = new URL(spec);
//打开链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//得到状态码
int status = conn.getResponseCode();
if (status == 200) {
//链接成功
//开始下载
//获得流
BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("a3.jpg"));
byte[] b = new byte[1024];
int len = 0;
while ((len = bis.read(b)) != -1) {
bos.write(b, 0, len);
}
//关流
bos.flush();
bos.close();
bis.close();
//关闭连接
conn.disconnect();
}else{
System.out.println("成妾做不到啊");
}
}
 
}
下面是一个本地的写法:
  
  
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
 
public class HttpURLConnectionDemo02 {
 
public static void main(String[] args) throws Exception {
String spec = "http://127.0.0.1:8080/day028_web/LoginServlet";
String userName = "Mixm";
String passWord = "0906";
String strSend = "userName=" + userName+"&passWord="+ passWord;
//确定资源
URL url = new URL(spec);
//得到链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//发送数据
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.write(strSend.getBytes());
//获得状态码
int status = conn.getResponseCode();
//判断状态码
if (status == 200) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
System.out.println(br.readLine());
br.close();
} else {
System.out.println("臣妾做不到啊");
}
os.close();
conn.disconnect();
}
 
}
解决编码的问题: 在上面的代码中,传递给服务器的值,设置传递给服务器编码的格式:
URLEncoder.encode(username, "utf-8")   ---推荐使用
URLDecoder.decode(username, "utf-8")   ---使用的少。如果客户端使用该方法,那么在服务端必须使用相同的方法转换过来
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值