URL下載數據、模擬登陸或上傳

URL下載數據:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class UrlDownLoad {
//從網上或服務器下載數據
public static void main(String[] args) {
         String path="http://img4.duitang.com/uploads/item/201306/20/20130620221932_FVnZK.thumb.600_0.jpeg";
     try {
     //將網址封裝成url對象
URL url=new URL(path);
//創建鏈接,用url裏面的openConnection方法打開鏈接。
HttpURLConnection connection=(HttpURLConnection) url.openConnection();
//設置一些屬性
//1.請求方式,默認爲GET必須爲大寫
connection.setRequestMethod("GET");
connection.setDoInput(true);//可讀默認true
connection.setDoOutput(true);//可寫,默認false
connection.setReadTimeout(5000);//請求超時時間
connection.connect();//鏈接
int code=connection.getResponseCode();//得到響應碼:通常是200
//7判斷是否爲200,表示成功
if(code==200){
//讀取服務器發送過來的數據,得到讀取管道
InputStream is=connection.getInputStream();
//存放地址
OutputStream os=new FileOutputStream("e:\\600_0.jpeg");
byte []a=new byte[1024];//緩衝數組
int len=-1;
while((len=is.read(a))!=-1){
os.write(a, 0, len);
}
is.close();
os.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
模擬登陸:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class UrlUpLoad {
    //url模擬登陸,能夠變一下變成上傳數據
public static void main(String[] args) {
String path = "http://localhost:8080/MyServer/login";
      try {
URL url=new URL(path);
HttpURLConnection connection=(HttpURLConnection) url.openConnection();
//上傳請求方式爲Post,大寫
connection.setRequestMethod("POST");
//要設置可寫,由於默認爲false
connection.setDoOutput(true);
//將數據寫到流中。
//先得到寫入流。
OutputStream os=connection.getOutputStream();
os.write("username=admin&userpwd=111".getBytes());
connection.connect();
int code=connection.getResponseCode();//響應碼200
if(code==HttpURLConnection.HTTP_OK){//表明200
//打印服務器那邊返回的信息
          InputStream is=connection.getInputStream();
              byte[]a=new byte[1024];
              int len=is.read(a);
              System.out.println(new String(a,0,len));
              is.close();
}
        os.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
相關文章
相關標籤/搜索