在Java編程中,HTTP通信是一個非常重要的方面。而HTTP請求中最常用的兩種方式是get請求和post請求。
get請求是一種非常簡單的請求方式,它通過URL的參數(shù)傳遞數(shù)據(jù)。在Java中使用get請求可以使用URLConnection類或者apache的HttpClient庫。
public static void main(String[] args) throws Exception { URL url = new URL("http://www.example.com/?param1=value1¶m2=value2"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); }
而post請求則是通過向服務(wù)器發(fā)送數(shù)據(jù)的方式來請求資源。在Java中,我們需要使用URLConnection類或者apache的HttpClient庫來發(fā)送post請求。
public static void main(String[] args) throws Exception { URL url = new URL("http://www.example.com/"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); String request = "param1=value1¶m2=value2"; writer.write(request); writer.flush(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); writer.close(); }
以上是在Java中實現(xiàn)get和post請求的兩種方式。由于URLConnection類已經(jīng)被標(biāo)記為過時,因此在實際開發(fā)中建議使用HttpClient庫來執(zhí)行HTTP請求。
下一篇jquery3在線手冊