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

3.       Java application的代码

package com.pat.postrequestemulator;

importjava.io.BufferedReader;

importjava.io.DataInputStream;

importjava.io.File;

import java.io.FileInputStream;

importjava.io.InputStream;

importjava.io.InputStreamReader;

importjava.io.OutputStream;

importjava.io.Serializable;

importjava.net.HttpURLConnection;

importjava.net.URL;

importjava.util.ArrayList;

public classPostRequestEmulator

{

public static void main(String[] args)throws Exception

{

// 设定服务地址

String serverUrl ="http://127.0.0.1:8080/test/upload";

// 设定要上传的普通Form Field及其对应的value

ArrayList<FormFieldKeyValuePair>ffkvp = new ArrayList<FormFieldKeyValuePair>();

ffkvp.add(newFormFieldKeyValuePair("username", "Patrick"));

ffkvp.add(newFormFieldKeyValuePair("password", "HELLOPATRICK"));

ffkvp.add(newFormFieldKeyValuePair("hobby", "Computer programming"));

// 设定要上传的文件

ArrayList<UploadFileItem>ufi = new ArrayList<UploadFileItem>();

ufi.add(newUploadFileItem("upload1", "E:\\Asturias.mp3"));

ufi.add(newUploadFileItem("upload2", "E:\\full.jpg"));

ufi.add(newUploadFileItem("upload3", "E:\\dyz.txt"));

HttpPostEmulator hpe = newHttpPostEmulator();

String response =hpe.sendHttpPostRequest(serverUrl, ffkvp, ufi);

System.out.println("Responsefrom server is: " + response);

}

}

classHttpPostEmulator

{

//每个post参数之间的分隔。随意设定,只要不会和其他的字符串重复即可。

private static final String BOUNDARY ="----------HV2ymHFg03ehbqgZCaKO6jyH";

public StringsendHttpPostRequest(String serverUrl,

ArrayList<FormFieldKeyValuePair>generalFormFields,

ArrayList<UploadFileItem>filesToBeUploaded) throws Exception

{

// 向服务器发送post请求

URL url = newURL(serverUrl/*"http://127.0.0.1:8080/test/upload"*/);

HttpURLConnection connection= (HttpURLConnection) url.openConnection();

// 发送POST请求必须设置如下两行

connection.setDoOutput(true);

connection.setDoInput(true);

connection.setUseCaches(false);

connection.setRequestMethod("POST");

connection.setRequestProperty("Connection","Keep-Alive");

connection.setRequestProperty("Charset","UTF-8");

connection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);

// 头

String boundary = BOUNDARY;

// 传输内容

StringBuffer contentBody =new StringBuffer("--" + BOUNDARY);

// 尾

String endBoundary ="\r\n--" + boundary + "--\r\n";

OutputStream out =connection.getOutputStream();

// 1. 处理文字形式的POST请求

for(FormFieldKeyValuePairffkvp : generalFormFields)

{

contentBody.append("\r\n")

.append("Content-Disposition: form-data; name=\"")

.append(ffkvp.getKey() + "\"")

.append("\r\n")

.append("\r\n")

.append(ffkvp.getValue())

.append("\r\n")

.append("--")

.append(boundary);

}

String boundaryMessage1 =contentBody.toString();

out.write(boundaryMessage1.getBytes("utf-8"));

// 2. 处理文件上传

for(UploadFileItem ufi :filesToBeUploaded)

{

contentBody = newStringBuffer();

contentBody.append("\r\n")

.append("Content-Disposition:form-data; name=\"")

.append(ufi.getFormFieldName() +"\"; ")   // form中field的名称

.append("filename=\"")

.append(ufi.getFileName() +"\"")                //上传文件的文件名,包括目录

.append("\r\n")

.append("Content-Type:application/octet-stream")

.append("\r\n\r\n");

StringboundaryMessage2 = contentBody.toString();

out.write(boundaryMessage2.getBytes("utf-8"));

// 开始真正向服务器写文件

File file = newFile(ufi.getFileName());

DataInputStream dis= new DataInputStream(new FileInputStream(file));

int bytes = 0;

byte[] bufferOut =new byte[(int) file.length()];

bytes =dis.read(bufferOut);

out.write(bufferOut,0, bytes);

dis.close();

contentBody.append("------------HV2ymHFg03ehbqgZCaKO6jyH");

StringboundaryMessage = contentBody.toString();

out.write(boundaryMessage.getBytes("utf-8"));

//System.out.println(boundaryMessage);

}

out.write("------------HV2ymHFg03ehbqgZCaKO6jyH--\r\n".getBytes("UTF-8"));

// 3. 写结尾

out.write(endBoundary.getBytes("utf-8"));

out.flush();

out.close();

// 4. 从服务器获得回答的内容

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);

return strResponse;

}

}

classFormFieldKeyValuePair implements Serializable

{

private static final longserialVersionUID = 1L;

// The form field used for receivinguser's input,

// such as "username" in "<inputtype="text"/>"

private String key;

// The value entered by user in thecorresponding form field,

// such as "Patrick" the abovementioned formfield "username"

private String value;

public FormFieldKeyValuePair(Stringkey, String value)

{

this.key = key;

this.value = value;

}

public String getKey()

{

return key;

}

public void setKey(String key)

{

this.key = key;

}

public String getValue()

{

return value;

}

public void setValue(String value)

{

this.value = value;

}

}

classUploadFileItem implements Serializable

{

private static final longserialVersionUID = 1L;

// The form field name in a form used foruploading a file,

// such as "upload1" in "<inputtype="file"/>"

private String formFieldName;

// File name to be uploaded, thefileName contains path,

// such as "E:\\some_file.jpg"

private String fileName;

public UploadFileItem(StringformFieldName, String fileName)

{

this.formFieldName =formFieldName;

this.fileName = fileName;

}

public String getFormFieldName()

{

return formFieldName;

}

public void setFormFieldName(StringformFieldName)

{

this.formFieldName =formFieldName;

}

public String getFileName()

{

return fileName;

}

public void setFileName(StringfileName)

{

this.fileName = fileName;

}

}

4.       运行结果

运行PostRequestEmulator之前,服务器的upload目录下的情况:

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

 

运行PostRequestEmulator后,服务器的upload目录下的情况:

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

 

PostRequestEmulator从服务端得到的反馈情况:

Response fromserver is: OK

Tomcat控制台输出:

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

 

如果上传的文件中有大于1M的情况,第二次执行PostRequestEmulator的时候,就会在temp目录中产生临时文件。

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

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