HttpClient menggunakan metode pos untuk mengirimkan kode sumber data:
Salinan kode adalah sebagai berikut:
Posting Paket;
impor java.io.ioException;
impor org.apache.commons.httpclient.header;
impor org.apache.commons.httpclient.httpClient;
impor org.apache.commons.httpclient.httpException;
impor org.apache.commons.httpclient.httpstatus;
impor org.apache.commons.httpclient.namevaluepair;
impor org.apache.commons.httpclient.methods.postmethod;
POSTHTTP kelas publik {
/**
* @param args
*/
public static void main (string [] args) {
// TODO Stub Metode yang dihasilkan otomatis
HttpClient httpClient = httpClient baru ();
String url = "http://193.167.13.21/setup.cgi";
PostMethod PostMethod = New PostMethod (URL);
// Isi nilai dari setiap bidang formulir
Namevaluepair [] data = {
new namevaluePair ("id", "11"),
new namevaluepair ("mtg", "0"),
new namevaluePair ("havecookie", "0"),
NamevaluePair baru ("backid", "30"),
New NamevaluePair ("PSW", "Kata Sandi")
};
// Masukkan nilai formulir ke dalam postmethod
postmethod.setRequestBody (data);
// Jalankan postmethod
int statuscode = 0;
mencoba {
statusCode = httpclient.executeMethod (postmethod);
} catch (httpException e) {
// TODO Blok tangkapan yang dihasilkan otomatis
e.printstacktrace ();
} catch (ioException e) {
// TODO Blok tangkapan yang dihasilkan otomatis
e.printstacktrace ();
}
// httpClient tidak dapat secara otomatis menangani penerusan untuk permintaan yang memerlukan layanan selanjutnya seperti pos dan put.
// 301 atau 302
if (statuscode == httpstatus.sc_moved_permanently || statuscode == httpstatus.sc_moved_temporly)
{
// ambil alamat kemudi dari awal
Header locationHeader = postmethod.getResponseHeader ("location");
Lokasi String = NULL;
if (locationHeader! = null) {
location = locationHeader.getValue ();
System.out.println ("Halaman tersebut dialihkan ke:" + lokasi);
}
kalau tidak {
System.err.println ("Nilai bidang lokasi adalah nol.");
}
kembali;
}
kalau tidak
{
System.out.println (postmethod.getstatusLine ());
String str = "";
mencoba {
str = postmethod.getResponseBodyAsstring ();
} catch (ioException e) {
// TODO Blok tangkapan yang dihasilkan otomatis
e.printstacktrace ();
}
System.out.println (str);
}
postmethod.releaseconnection ();
kembali ;
}
}
// Ini adalah informasi login dari proses otentikasi pengguna
Paket JAR yang diperlukan:
1. Commons-httpclient-3.1-rc1.zip http://jakarta.apache.org/commons/httpclient/downloads.html
2. Commons-codec-1.3.jar http://jakarta.apache.org/site/downloads/downloads_commons-codec.cgi
3.