java解析http請求
public static void testPost() throws IOException {
/**
* 首先要和URL下的URLConnection對話。 URLConnection可以很容易的從URL得到。比如: // Using
* java.net.URL and //java.net.URLConnection
*/
URL url = new URL("http地址");
URLConnection connection = url.openConnection();
/**
* 然後把連線設為輸出模式。URLConnection通常作為輸入來使用,比如下載一個Web頁。
* 通過把URLConnection設為輸出,你可以把資料向你個Web頁傳送。下面是如何做:
*/
connection.setDoOutput(true);
/**
* 最後,為了得到OutputStream,簡單起見,把它約束在Writer並且放入POST資訊中,例如: ...
*/
OutputStreamWriter out = new OutputStreamWriter(connection
.getOutputStream(), "8859_1");
out.write("username=kevin&password=*********"); //post的關鍵所在!
// remember to clean up
out.flush();
out.close();
/**
* 這樣就可以傳送一個看起來象這樣的POST:
* POST /jobsearch/jobsearch.cgi HTTP 1.0 ACCEPT:
* text/plain Content-type: application/x-www-form-urlencoded
* Content-length: 99 username=bob password=someword
*/
// 一旦傳送成功,用以下方法就可以得到伺服器的迴應:
String sCurrentLine;
String sTotalString;
sCurrentLine = "";
sTotalString = "";
InputStream l_urlStream;
l_urlStream = connection.getInputStream();
// 傳說中的三層包裝阿!
BufferedReader l_reader = new BufferedReader(new InputStreamReader(
l_urlStream));
while ((sCurrentLine = l_reader.readLine()) != null) {
sTotalString += sCurrentLine + "/r/n";
}
System.out.println(sTotalString);
}
public static void main(String[] args) throws IOException {
testPost();
}
}