---
# System prepended metadata

title: HTTP Requests
tags: [Java]

---

# HTTP
(RFC 7231)
### URL format (RFC 1738)
```
https://www.example.com:8080/path/of/your/file.txt?query1=v1&query2=v2#Section
1       2               3    4                    5                    6
    
1. scheme (protocol) (協定類型)
2. domain (網域)
3. specified port (埠號，又稱端口) (default: http:80,https:443)
4. path-of-the-target-file (請求目標檔案路徑)
5. query key,value pairs (參數)
6. Fragments (片段)
```

這裡不太講HTTP請求的細節。

```
Client "Request" to Server.
Server "Response" to Client. 
```
### Request Methods
GET       //retrieve datas
POST      //submit datas
HEAD
PUT
DELETE
CONNECT
OPTIONS
TRACE
PATCH
    
### Request Headers
User-Agent
Content-Type
Cookie
Connection
...
    
### Response headers
Set-Cookie
    
### Response Codes
https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
200 OK
401 Unauthorized
403 Forbidden
404 Not Found
408 Request Timeout
500 Internal Server Error
502	Bad Gateway
503	Service Unavailable
...
    
### HTTP Cookie
HTTP Cookie，簡稱Cookie，是請求網站時由Server建立並存放在Client的小文字檔案。
存於Header中。
- Client提供Cookie給Server: 
   Header Field: Cookie
- Server更改Client的Cookie:
    Header Field: Set-Cookie

Cookie使Server能在Client儲存資訊, 如Session

格式: k1: v1; k2: v2; k3: v3; ...

### 範例
GET https://github.com
```java=
try {
    String urlString = "https://github.com";
            
    URL url = new URL(urlString);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");

    System.out.println(connection.getResponseCode());
    
    System.out.println(new String(connection.getInputStream().readAllBytes()));
} catch (IOException ex) {
    ex.printStackTrace();
}
```
<!--
原神每日簽到
```java=
String url = "https://sg-hk4e-api.hoyolab.com/event/sol/sign";
String act_id = "e202102251931481";
String lang = "en-us";
        
String finalURL = url + "?act_id=" + act_id + "&lang=" + lang;

Map<String, String> cookieMap = new HashMap<>();
cookieMap.put("ltoken_v2", "your-token");
cookieMap.put("ltuid_v2", "your-uid");

String cookie = "";
for (Map.Entry<String, String> kv : cookieMap.entrySet()) {
    cookie += kv.getKey() + "=" + kv.getValue() + ";";
}
try {
    HttpURLConnection connection = (HttpURLConnection) new URL(finalURL).openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Cookie", cookie);

    System.out.println(connection.getResponseCode());
    System.out.println(new String(connection.getInputStream().readAllBytes()));
} catch (IOException ex) {
    ex.printStackTrace();
}
```

```yml=
"Genshin Impact": 
  "URL": https://sg-hk4e-api.hoyolab.com/event/sol/sign 
  "act_id": e202102251931481
"Honkai: Star Rail": 
  "URL": https://sg-public-api.hoyolab.com/event/luna/os/sign 
  "act_id": e202303301540311 
"Honkai Impact 3":
  "URL": https://sg-public-api.hoyolab.com/event/mani/sign
  "act_id": e202110291205111
```