不管是要做爬蟲,還是是要無縫連接網際網路的服務,都需要利用程式來實作瀏覽器的動作。
雖然上週才剛發一篇 Android HTTP POST
但因為 Android 函式庫本身已經內含 Apache 的 HttpClient 套件,所以實作起來稍微簡單一點
而在純 Java Application 的環境中,如果沒辦法用 Apache 的套件的話,就必須自己用別的方法處理了。
參考資料:
1、java HttpURLConnection來實作get及post動作
2、HTTPURLConnection
從參考資料可以看出,純 Java 環境是可以利用 HttpUrlConnection 來實作。
以下是範例程式:
HttpUrlPost.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; public class HttpUrlPost { public String postData (String url, String contentType, String data) throws MalformedURLException, IOException { URL endpoint = new URL(url); HttpURLConnection httpConnection = (HttpURLConnection) endpoint.openConnection(); httpConnection.setRequestMethod( "POST" ); httpConnection.setDoInput( true ); httpConnection.setDoOutput( true ); httpConnection.setRequestProperty( "Content-Type" , contentType); // Add post data if (data != null && data.length() > 0 ) { httpConnection.setRequestProperty( "Content-Length" , String.valueOf(data.length())); DataOutputStream dos = null ; try { dos = new DataOutputStream(httpConnection.getOutputStream()); // Use utf-8 encoding for the post data. dos.write(data.getBytes(Charset.forName( "utf-8" ))); dos.flush(); } finally { if (dos != null ) dos.close(); } } // Read the response from server InputStreamReader isr = null ; BufferedReader br = null ; String line = null ; StringBuilder sb = new StringBuilder(); try { isr = new InputStreamReader(httpConnection.getInputStream()); br = new BufferedReader(isr); while ( (line = br.readLine()) != null ) { sb.append(line); } } finally { if (br != null ) br.close(); if (isr != null ) isr.close(); } return sb.toString(); } } |
這裡是直接假設要送的是 POST 的 request,然後強制用 UTF-8 編碼來轉譯要送的 POST 字串。
要呼叫的時候,假設要送的 POST 資料是 JSON 的字串,可以用下面的方式呼叫。
1 2 3 4 5 6 7 8 |
// Url which the request is sent to // JSON format string which will be attached in the POST request JSONObject requestJSON = new JSONObject(); requestJSON.put( "statuscode" , 200 ); // Send the request HttpUrlPost post = new HttpUrlPost(); Strin response = httpPost.postData(url, "application/json" , requestJSON.toString()); |
沒有留言:
張貼留言