一個簡單的java https client 範例
public String sendHTTPS(String url, String queryStr, String host, int port) {
String ret = "";
String USER_AGENT = "Mozilla/5.0";
String httpsURL = "https://"+host + url;
try {
URL myUrl = new URL(httpsURL);
HttpsURLConnection conn;
conn = (HttpsURLConnection)myUrl.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
try {
String urlParameters = queryStr;
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String inputLine;
while ((inputLine = br.readLine()) != null) {
ret += inputLine;
}
br.close();
System.out.println("SendHTTPS response: "+ret );
} catch (Exception e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return ret;
}
使用方式
sendHTTPS("/ok.php" ,"query=something" ,"127.0.0.1" ,443);
相當於使用瀏覽器打開 https://127.0.0.1/ok.php 並挾帶 POST 資訊 query=something