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") ---使用的少。如果客户端使用该方法,那么在服务端必须使用相同的方法转换过来