首先需要了解网络协议,HTTP协议是互联网上使用最广泛的协议,任何在网络上传输数据必须遵循某种协议。请求方式常用两种GET和POST请求,请求完成状态码很多,经常见到的是404找不到资源文件,200是请求成功。网络请求两种:第一种:原生HttpURLConnection,第二种:apache的.HttpClient。
大致提了一下需要用到的东西,接下来看一下详细的比较:
请求方式比较(GET POST)
GET 传输量小,速度快,明文显示URL不安全。
POST传输量接近无限制,速度慢,数据放在HTML HEADER内一起传送到服务端URL地址,对用户不可见,较GET安全。
网络请求比较:(HttpURLConnection HttpClient )
HttpURLConnection书写时比较繁琐,但运行效率较高
HttpClient书写变的容易,并且便于理解,运行效率不如HttpURLConnection
HttpURLConnection
GET请求:
抽象类 URLConnection
是所有类的超类,它代表应用程序和 URL 之间的通信链接。此类的实例可用于读取和写入此 URL 引用的资源。通常,创建一个到 URL 的连接需要几个步骤:
1.使用URL定位到网络资源(URL url = new URL(URL);)
2.使用ULR的openConnection与资源建立连接(HttpURLConnection conn = (HttpURLConnection) url.openConnection();)
3.设置请求的参数和请求方式(conn.setRequestMethod("GET"))
4.读取服务器资源的流(conn.getInputStream())
为了展示方便,建立了一个HttpUtil勉强算工具类
HttpUtil.java
public class HttpUtil {
public static byte[] getImage(String URLpath) {
ByteArrayOutputStream baos=null;
InputStream is=null;
try {
// 1.创建URL对象(统一资源定位符) 定位到网络上了
URL url = new URL(URLpath);
// 2.创建连接对象
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 3.设置参数
conn.setDoInput(true);// 设置能不能读
conn.setDoOutput(true);// 设置能不能写
conn.setRequestMethod("GET");// 请求方式必须大写
conn.setReadTimeout(5000);// 连接上了读取超时的时间
conn.setConnectTimeout(5000);// 设置连接超时时间5s
// 获取响应码
int code = conn.getResponseCode();
// 4.开始读取
if(code==200){
//5读取服务器资源的流
is= conn.getInputStream();
//准备内存输出流 临时存储的
baos = new ByteArrayOutputStream();
byte buff[] = new byte[1024];
int len=0;
while((len=is.read(buff))!=-1){
baos.write(buff,0,len);
baos.flush();
}
}
return baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
finally{
//关流
if(is!=null&&baos!=null){
try {
is.close();
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
test.java
public class URLRequestImage {
public static void main(String[] args) throws Exception {
String url = "https://www.baidu.com/img/bdlogo.png";
//工具类请求完成的字节数组
byte[] image = HttpUtil.getImage(url);
//切割URL字符串得到名字和扩展名
String fileName = url.substring(url.lastIndexOf("/")+1);
File file = new File("c:/image/"+fileName+"");
FileOutputStream fos = new FileOutputStream(file);
fos.write(image);
fos.close();
}
}
至此java原生的HttpURLConnection结束。
POST请求:
URL url = new URL(path);
// 2.创建连接对象
HttpURLConnection conn = (HttpURLConnection) url.openConnection()
conn.setRequestMethod("POST");//必须大写
// 给服务器写信息 String param是封装了用户名和密码 格式是:user pw
OutputStream os = conn.getOutputStream();
os.write(param.getBytes());
HttpClient
GET请求:
它并不能想HttpURLConnection那样直接就可以使用,由于是第三方的,所以需要导入jar包,网上很多,这里就不给出了。下面的Demo使用了线程,接口回调方面的知识
HttpUtil.java
public class HttpUtil {
public static void getImage(final String url, final CallBack callBack) {
new Thread(new Runnable() {
@Override
public void run() {
// 打开一个浏览器
HttpClient client = new DefaultHttpClient();
//在地址栏上输入地址
HttpGet get = new HttpGet(url);
try {
//敲击回车
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
byte[] byteArray = EntityUtils.toByteArray(entity);
//接口用于主函数回调
callBack.getByteImage(byteArray);
}
} catch (Exception e) {
// TODO: handle exception
}
}
}).start();
}
interface CallBack {
void getByteImage(byte[] b);
}
}
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">Test.java</span>
public class URLRequestImage {
public static void main(String[] args) throws Exception {
String url = "https://www.baidu.com/img/bdlogo.png";
HttpUtil.getImage(url, new CallBack() {
@Override
public void getByteImage(byte[] b){
try {
File file = new File("C:/img/a.png");
FileOutputStream fos = new FileOutputStream(file);
fos.write(b);
fos.flush();
System.out.println("图片下载成功");
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
因为本人只有C盘一个盘符,这里曾经多次尝试写入C盘根目录,但每次都报FileNotFoundException拒绝访问,改成C盘下的一个文件夹即可。
POST请求:
HttpPost post = new HttpPost(url);
//定义NameValuePair对象
List<NameValuePair> list = new ArrayList<NameValuePair>();
BasicNameValuePair pair1 = new BasicNameValuePair("userName", "张三");
BasicNameValuePair pair2 = new BasicNameValuePair("userPassword", "123");
//添加到List集合
list.add(pair1);
list.add(pair2);
//
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list);
//设置Post请求entity entity可以理解为大箱子
post.setEntity(entity);
总结:无论那种网络请求GET都是很简单并且很常见的,而POST的请求却很繁琐,HttpURLconnection用流向服务器里写,HttpClient是给HttpPost引用setEntity。