Java应用程序模拟向Servlet发送POST请求

在某些情况下,需要用Java applicatioin来模拟form,向服务器(本文以servlet为例)发送http post请求,包括提交表单域中的数据以及上传文件。如果仅仅是传递form中的数据,而不包含上传文件,那是很简单的,比如Java application可以这么写:

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”这样的普通信息,同时还要上传文件,事情就复杂得多。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wypgdf.html