HttpUrlConnection是谷歌公司開發(fā)推薦的一種編寫客戶端的開源框架
以GET請求方式在網(wǎng)上下載一張圖片
package com.qf.demo5;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* 谷歌官方推薦的 HttpUrlConnection
* @author Administrator
*/
public class Test {
public static void main(String[] args) {
InputStream is = null;
FileOutputStream fos =null;
try {
// 1URL 統(tǒng)一資源定位符
URL url = new URL("http://photocdn.sohu.com/20150610/mp18368185_1433925691994_2.jpg");
// 2
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 3 設(shè)定 請求方式
connection.setRequestMethod("GET");
// 4 連接服務(wù)器
connection.connect();
// 5 接收響應(yīng)
// 判斷 請求是否成功, 響應(yīng)的狀態(tài) 狀態(tài)碼 200 請求響應(yīng)成功了
// 200 響應(yīng)成功 404 找不到頁面 500 服務(wù)器錯誤
if(connection.getResponseCode()==200){
// 讀取
is = connection.getInputStream();
fos = new FileOutputStream(new File("w.jpg"));
byte[] bs = new byte[1024];
int num = 0;
while((num = is.read(bs))!=-1){
fos.write(bs, 0, num);
fos.flush();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(is!=null){
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
POST請求方式訪問服務(wù)端
package com.qf.demo5;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* post 請求
* @author Administrator
*
*/
public class Test3 {
public static void main(String[] args) {
BufferedReader reader = null;
try {
URL url = new URL("http://localhost:8080/Day28_03/LoginServlet");
// 2
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 3
connection.setRequestMethod("POST");
// 是否允許修改 地址 (是否允許在地址中追加 參數(shù))
connection.setDoOutput(true);// false 默認(rèn)不允許修改
connection.setDoInput(true);// true 默認(rèn)就是允許讀取的
// 4 修改 追加 參數(shù)
OutputStream os = connection.getOutputStream();// 從這個流 向 conntion中取添加參數(shù)
os.write("useName=zhangasan&pwd=123".getBytes());
os.flush();
// 5 連接(可以寫 可以不寫 不寫 默認(rèn)幫助執(zhí)行 連接操作)
//connection.connect();
// 6 讀取響應(yīng)內(nèi)容
if(connection.getResponseCode()==200){
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
String result = reader.readLine();
System.out.println("服務(wù)器回復(fù)的數(shù)據(jù)="+result);
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(reader!=null){
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}