Skip to content

Instantly share code, notes, and snippets.

@tjjh89017
Created December 30, 2014 13:02
Show Gist options
  • Save tjjh89017/a043c65d591e754ebbf8 to your computer and use it in GitHub Desktop.
Save tjjh89017/a043c65d591e754ebbf8 to your computer and use it in GitHub Desktop.
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.Scanner;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;
public class Main {
//Regex
static String pattern_str = "^http://([^/:]*):?(\\d{1,5})?/(.*)$";
public static void main(String args[]){
Pattern pattern = Pattern.compile(pattern_str); //pattern_str 轉換成 Regex規則
Scanner scan = new Scanner(System.in);
Scanner inputFile; //使指標去除HEADER
String input = scan.next();
Matcher matcher = pattern.matcher(input); //匹配結果
if(matcher.matches()){ //匹配結果符合
String hostname = matcher.group(1); //pattern_str中第一個()內容 = hostname
String port_s = matcher.group(2); //pattern_str中第二個()內容 = port
String filename = matcher.group(3); //pattern_str中第三個()內容 = filename
int port = 80; //預設port
if(port_s != null && !port_s.equals("")){
port = Integer.parseInt(port_s);
}
System.out.println("host = " + hostname);
System.out.println("port = " + port);
String header = String.format(
"GET %s HTTP/1.1\r\nHost: %s\r\n\r\n",
filename,
hostname);
/*
GET {filename} HTTP/1.1\r\n
Host: {hostname}\r\n
\r\n
*/
try{
Socket sock = new Socket(hostname, port);
byte[] b = new byte[1024]; //接收byte的buffer
int len = 0; //接收的資料長度
String[] a = filename.split("/");
FileOutputStream out_file = new FileOutputStream(a[a.length-1]); //找出最後一個"/"後的名稱為檔案名
// 送出 the header from our input
BufferedOutputStream out = new BufferedOutputStream(sock.getOutputStream());
out.write(header.getBytes());
out.flush();
//將寫入的檔案指標先用Scanner.nextLine()移動一次,則剛好可以去除HEADER
inputFile = new Scanner(sock.getInputStream());
inputFile.nextLine(); //It's magic!
//接收從server回傳的檔案
BufferedInputStream in = new BufferedInputStream(sock.getInputStream());
while((len = in.read(b)) > 0){ //每次回傳len個bytes 直到沒有回傳為止
out_file.write(b, 0, len);
// write the b to the file
}
//關閉
out_file.close();
in.close();
out.close();
sock.close();
System.out.println("The download is finished.");
}catch(IOException e){
e.printStackTrace();
System.out.println("Error!");
}
}else{ //沒有匹配結果
System.out.println("No match.");
}
}
}
// curl-like
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment