HTTP

參考資料:(https://stackoverflow.com/questions/3324717/sending-http-post-request-in-java)

URL

getURL(String url)

return new URL(url);

HTTPS

ignoreVerifierAndSetSSLSocketByHTTPS(URL target)

if (EProtocol.HTTPS.toString().equalsIgnoreCase(target.getProtocol())) {
    HttpsURLConnection.setDefaultSSLSocketFactory(getSSLContext().getSocketFactory());
    HttpsURLConnection.setDefaultHostnameVerifier(hv);
}

HttpURLConnection

getHttpURLConnection(URL url, String bodyContent, EContentType contentType)

HttpURLConnection connection = getHttpURLConnection(url, contentType);

DataOutputStream dataOs = new DataOutputStream(connection.getOutputStream());
dataOs.write(bodyContent.getBytes("UTF-8"));
dataOs.flush();
dataOs.close();

return connection;

Form Data

注意: Content-Type

postFromData(String url, Map<String,String> map)

Map<String,String> arguments = new HashMap<>();
arguments.put("username", "root");
arguments.put("password", "sjh76HSn!"); // This is a fake password obviously
StringJoiner sj = new StringJoiner("&");
for(Map.Entry<String,String> entry : arguments.entrySet())
    sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" 
         + URLEncoder.encode(entry.getValue(), "UTF-8"));
byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8);
int length = out.length;

http.setFixedLengthStreamingMode(length);
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
http.connect();
try(OutputStream os = http.getOutputStream()) {
    os.write(out);
}
// Do something with http.getInputStream()

JSON String

注意: Content-Type

postJson(String url, String toJson)

byte[] out = "{\"username\":\"root\",\"password\":\"password\"}" .getBytes(StandardCharsets.UTF_8);
int length = out.length;

http.setFixedLengthStreamingMode(length);
http.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
http.connect();
try(OutputStream os = http.getOutputStream()) {
    os.write(out);
}
// Do something with http.getInputStream()
URL url = "url";

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

connection.setRequestMethod(ERequestMethod.POST.toString());

//set header
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Content-Language", "UTF-8");

//setting
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setConnectTimeout(CSystemFunctionData.getApiTimeout()*1000);
connection.setReadTimeout(CSystemFunctionData.getApiTimeout()*1000);

//set body
DataOutputStream dataOs = new DataOutputStream(connection.getOutputStream());
dataOs.write(bodyContent.getBytes("UTF-8"));
dataOs.flush();
dataOs.close();

Last updated