JDK-api

上传解析的实现简单说一下:
通过ServletRequest类的getInputStream()方法获得一个客户端向服务器发出的数据流、分析上传的文件格式,根据分析结果将多个文件依次输出服务器端的目标文件中。
格式类似下面:

//文件分隔符
-----------------------------7d226137250336
//文件信息头
Content-Disposition: form-data; name="FILE1"; filename="C:\Documents and Settings\Administrator.TIMBER-4O6B0ZZ0\My Documents\tt.sql"
Content-Type: text/plain
//源文件内容
create table info(
content image null);
//下一个文件的分隔符
-----------------------------7d226137250336
Content-Disposition: form-data; name="FILE2"; filename=""
Content-Type: application/octet-stream
-----------------------------7d226137250336


每个表单提交的元素都有分隔符将其分隔,其提交的表单元素的名称和对应的输入值之间也有特殊的字符将其分隔开


例1:POST,传参数
另外,我再给出一个朋友写的机器人程序,恶搞飞信网站的例子。欢迎多多运行,搞死这些骗子:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;

import com.verisign.uuid.UUID;

/**
* 向一个飞信网站自动提交垃圾信息的程序,用空可以运行一下。
* @author wangpeng
*
*/
public class AutoSubmit {

/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
for(int i=0; i < 100000; i++){
post(i);
}
}

private static void post(int i) throws Exception{
String s = UUID.generate().toString();
String s1 = s.substring(0,2);
s = s1+ s.substring(s.length() - 3, s.length());

URL url = new URL("http://yfs88.sv10.sgedns.cn/yy/e/qq22.asp");// 提交地址
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);// 打开写入属性
httpURLConnection.setDoInput(true);// 打开读取属性
httpURLConnection.setRequestMethod("POST");// 设置提交方法
httpURLConnection.setConnectTimeout(50000);// 连接超时时间
httpURLConnection.setReadTimeout(50000);
httpURLConnection.connect();

BufferedWriter out = new BufferedWriter(new OutputStreamWriter(httpURLConnection.getOutputStream(), "GBK"));
out.write("name=" + s + i + //用户名不能重复
"&password=748" +
"&sex=很行" +
"&oicq=748748" +
"&icq=748748" +
"&msn=caonima" +
"&shengri=再不关门滚蛋,就把你们全关起来" +
"&home=已经盯上你们了");//要post的数据,多个以&符号分割
out.flush();
out.close();



//读取post之后的返回值
// BufferedReader in = new BufferedReader(new InputStreamReader((InputStream) httpURLConnection.getInputStream()));
// String line = null;
// StringBuilder sb = new StringBuilder();
// while ((line = in.readLine()) != null) {
// sb.append(line);
// }
// in.close();
// System.out.println("client:" + sb.toString());

httpURLConnection.disconnect();//断开连接

//
System.out.println("client post ok:" + i);
}

}



例2:
1. /**

2. * 采用java原生方式发送Http请求

3. *

4. * @param 目标url

5. * @param 发送内容

6. * @param 需要上传的消息头

7. * @param Http方法

8. * @param 内容类型

9. * @return

10. */

11. public static byte[] sendRequestV2(String url, String content,

12. Map<String, String> headers, String method, String contenttype)

13. {

14. byte[] result = null;

15.

16. try

17. {

18. HttpURLConnection httpConn = (HttpURLConnection) new URL(url)

19. .openConnection();

20.

21. // Should never cache GData requests/responses

22. httpConn.setUseCaches(false);

23.

24. // Always follow redirects

25. httpConn.setInstanceFollowRedirects(true);

26.

27. httpConn.setRequestMethod(method);

28. httpConn.setRequestProperty("Content-Type", contenttype);

29. httpConn.setRequestProperty("Accept-Encoding", "gzip");

30.

31. if (headers != null && headers.size() > 0)

32. {

33. Iterator<String> keys = headers.keySet().iterator();

34.

35. while (keys.hasNext())

36. {

37. String key = keys.next();

38. httpConn.setRequestProperty(key, headers.get(key));

39. }

40. }

41.

42. httpConn.setDoOutput(true);

43.

44. if (content != null)

45. httpConn.getOutputStream().write(content.getBytes("UTF-8"));

46.

47. System.setProperty("http.strictPostRedirect", "true");

48. httpConn.connect();

49.

50. ByteArrayOutputStream bout = new ByteArrayOutputStream();

51.

52. try

53. {

54. InputStream in = httpConn.getInputStream();

55.

56. byte[] buf = new byte[500];

57. int count = 0;

58.

59. while ((count = in.read(buf)) > 0)

60. {

61. bout.write(buf, 0, count);

62. }

63.

64. result = bout.toByteArray();

65. } catch (Exception ex)

66. {

67. ex.printStackTrace();

68. } finally

69. {

70. if (bout != null)

71. bout.close();

72. }

73.

74. System.clearProperty("http.strictPostRedirect");

75.

76. } catch (Exception e)

77. {

78. logger.error(e, e);

79. }

80.

81. return result; }

例3:post 上传文件以及参数
1. import java.io.BufferedReader;

2. import java.io.DataInputStream;

3. import java.io.DataOutputStream;

4. import java.io.File;

5. import java.io.FileInputStream;

6. import java.io.IOException;

7. import java.io.InputStream;

8. import java.io.OutputStream;

9. import java.net.HttpURLConnection;

10. import java.net.MalformedURLException;

11. import java.net.URL;

12.

13. public class ServletCom {

14.

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

16.

17. HttpURLConnection conn = null;

18. BufferedReader br = null;

19. DataOutputStream dos = null;

20. DataInputStream inStream = null;

21.

22. InputStream is = null;

23. OutputStream os = null;

24. boolean ret = false;

25. String StrMessage = "";

26. String exsistingFileName = "D:\\GHOST_Win7_x64_Ulitmate_V09.11_by_JUJUMAO.iso";

27. String fileName = "GHOST_Win7_x64_Ulitmate_V09.11_by_JUJUMAO.iso";

28.

29. String lineEnd = "\r\n";

30. String twoHyphens = "--";

31. String boundary = "----------------7d4a6d158c9";

32.

33. int bytesRead, bytesAvailable, bufferSize;

34.

35. byte[] buffer;

36.

37. int maxBufferSize = 1 * 1024 * 1024;

38.

39. String responseFromServer = "";

40.

41. String urlString = "http://192.168.6.18:5888/http/test";

42. FileInputStream fileInputStream = null;

43. try {

44. // ------------------ CLIENT REQUEST

45.

46. File file = new File(exsistingFileName);

47. fileInputStream = new FileInputStream(file);

48.

49. // open a URL connection to the Servlet

50.

51. URL url = new URL(urlString);

52.

53. // Open a HTTP connection to the URL

54.

55. conn = (HttpURLConnection) url.openConnection();

56.

57. // Allow Inputs

58. conn.setDoInput(true);

59.

60. // Allow Outputs

61. conn.setDoOutput(true);

62.

63. // Don't use a cached copy.

64. conn.setUseCaches(false);

65.

66. // Use a post method.

67. conn.setRequestMethod("POST");

68.

69. conn.setRequestProperty("Connection", "Keep-Alive");

70.

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

72.

73. StringBuffer sb = new StringBuffer();

74. sb.append(twoHyphens + boundary + lineEnd);

75. sb.append("Content-Disposition: form-data; name=\"file1\";" + " filename=\"" + fileName + "\"" + lineEnd);

76. sb.append(lineEnd);

77. sb.append(lineEnd + twoHyphens + boundary + twoHyphens + lineEnd);

78. long len = (long) sb.length() + file.length();

79. conn.setFixedLengthStreamingMode((int) len);// 在jdk7上提供了setFixedLengthStreamingMode(long xx)方法

80. // conn.setChunkedStreamingMode(1024 * 8);//可无缓存传大文件,但有些Http服务器不支持此方法

81. dos = new DataOutputStream(conn.getOutputStream());

82.

83. /**

84. * start:写一个键值对的格式

85. */

86. // dos.writeBytes(twoHyphens + boundary + lineEnd);

87. // dos.writeBytes("Content-Disposition: form-data; name=\"id\"" + lineEnd + lineEnd);

88. // dos.writeBytes("122");

89. // dos.writeBytes(lineEnd);

90. /**

91. * end: 写一个键值对

92. */

93.

94. dos.writeBytes(twoHyphens + boundary + lineEnd);

95. dos.writeBytes("Content-Disposition: form-data; name=\"file1\";" + " filename=\"" + fileName + "\""

96. + lineEnd);

97. dos.writeBytes(lineEnd);

98.

99. buffer = new byte[1024 * 8];

100. // read file and write it into form...

101. int i = 0;

102. int relength;

103. while ((relength = fileInputStream.read(buffer)) != -1) {

104. dos.write(buffer, 0, relength);

105. dos.flush();

106. }

107. // // send multipart form data necesssary after file data...

108.

109. dos.writeBytes(lineEnd + twoHyphens + boundary + twoHyphens + lineEnd);

110.

111. // close streams

112.

113. dos.flush();

114. dos.close();

115.

116. } catch (MalformedURLException ex) {

117. System.out.println("From ServletCom CLIENT REQUEST:" + ex);

118. } catch (IOException ioe) {

119. System.out.println("From ServletCom CLIENT REQUEST:" + ioe);

120. } finally {

121. if (fileInputStream != null) {

122. fileInputStream.close();

123. }

124. }

125.

126. // ------------------ read the SERVER RESPONSE

127.

128. try {

129. inStream = new DataInputStream(conn.getInputStream());

130. String str;

131. while ((str = inStream.readLine()) != null) {

132. System.out.println("Server response is: " + str);

133. System.out.println("");

134. }

135. inStream.close();

136.

137. } catch (IOException ioex) {

138. System.out.println("From (ServerResponse): " + ioex);

139.

140. }

141.

142. }

143. }
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页