package com.pat.postrequestemulator;
importjava.io.BufferedReader;
importjava.io.InputStream;
importjava.io.InputStreamReader;
importjava.io.OutputStreamWriter;
importjava.net.HttpURLConnection;
importjava.net.URL;
public classPostRequestEmulator
{
public static void main(String[] args)throws Exception
{
// 服務地址
URL url = newURL("http://127.0.0.1:8080/test/upload");
// 設定連接的相關參數
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStreamWriter out = newOutputStreamWriter(connection.getOutputStream(), "UTF-8");
// 向服務端發送key = value對
out.write("username=kevin&password=pass");
out.flush();
out.close();
// 獲取服務端的反饋
String strLine="";
String strResponse ="";
InputStream in =connection.getInputStream();
BufferedReader reader = newBufferedReader(new InputStreamReader(in));
while((strLine =reader.readLine()) != null)
{
strResponse +=strLine +"\n";
}
System.out.print(strResponse);
}
}
服務端的servlet可以這麼寫:
packagecom.pat.handlinghttprequestservlet;
importjava.io.IOException;
importjava.io.PrintWriter;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
public classHandlingHttpRequestServlet extends HttpServlet
{
private static final longserialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequestreq, HttpServletResponse resp)
throws ServletException, IOException
{
super.doGet(req, resp);
}
@Override
protected voiddoPost(HttpServletRequest req, HttpServletResponse resp)
throwsServletException, IOException
{
String username =req.getParameter("username"); //獲取username所對應的value
String password =req.getParameter("password"); //獲取password所對應的value
System.out.println("Thereceived username and password is: " + username + "/" +password);
// 向請求端發回反饋信息
PrintWriter out =resp.getWriter();
out.print("OK");
out.flush();
out.close();
super.doPost(req, resp);
}
}
一切看起來都不復雜。但是如果要模擬的表單,除了要向服務器傳遞如上面的“key = value”這樣的普通信息,同時還要上傳文件,事情就復雜得多。