不管是要做爬蟲,還是是要無縫連接網際網路的服務,都需要利用程式來實作瀏覽器的動作。
雖然上週才剛發一篇 Android HTTP POST
但因為 Android 函式庫本身已經內含 Apache 的 HttpClient 套件,所以實作起來稍微簡單一點
而在純 Java Application 的環境中,如果沒辦法用 Apache 的套件的話,就必須自己用別的方法處理了。
參考資料:
1、java HttpURLConnection來實作get及post動作
2、HTTPURLConnection
從參考資料可以看出,純 Java 環境是可以利用 HttpUrlConnection 來實作。
以下是範例程式:
HttpUrlPost.java
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 的字串,可以用下面的方式呼叫。
// Url which the request is sent to String url = "http://www.google.com/"; // 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());
沒有留言:
張貼留言