java模拟http请求,同时上传多个文件和参数(客户端)

package com.acconsys.base.util;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class HttpRequester {
    private static final String BOUNDARY = "-------45962402127348";
    private static final String FILE_ENCTYPE = "multipart/form-data";
public static void main(String[] args) {
	String filepath = "D:\\360安全浏览器下载\\plsqldev_2990.zip";
	String urlStr = "http://localhost:8080/chsService/FileUploadServlet";
	Map<String, String> textMap = new HashMap<String, String>();
	textMap.put("hahaha", "Capital-DocGen.zip");
	textMap.put("aaa", "D:\\server.zip");
	textMap.put("bbbb", "<?xml version='1.0' encoding='utf-8'?><root><parts><part number='设计Name' name='设计ShortDescription'  projectName='项目名'  version='设计版本' owner='设计创建人' type='设计类型' domain='所属域Name' status='设计状态'></part><part number='设计Name' name='设计ShortDescription'  projectName='项目名'  version='设计版本' owner='设计创建人' type='设计类型' domain='所属域Name' status='设计状态'></part><part number='设计Name' name='设计ShortDescription'  projectName='项目名'  version='设计版本' owner='设计创建人' type='设计类型' domain='所属域Name' status='设计状态'></part></parts></root>");
	Map<String, File> fileMap = new HashMap<String, File>();
	fileMap.put("myFile.zip", new File(filepath));
	post(urlStr, textMap, fileMap);

}
/**
 * 
 * @param urlStr http请求路径
 * @param params 请求参数
 * @param images 上传文件
 * @return
 */
    public static InputStream post(String urlStr, Map<String, String> params,
            Map<String, File> images) {
        InputStream is = null;
        
        try {
            URL url = new URL(urlStr);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            con.setConnectTimeout(5000);
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false);
            con.setRequestMethod("POST");
            con.setRequestProperty("Connection", "Keep-Alive");
            con.setRequestProperty("Charset", "UTF-8");
            con.setRequestProperty("Content-Type", FILE_ENCTYPE + "; boundary="
                    + BOUNDARY);
            
            StringBuilder sb = null;
            DataOutputStream dos = new DataOutputStream(con.getOutputStream());;
            if (params != null) {
                sb = new StringBuilder();
                for (String s : params.keySet()) {
                    sb.append("--");
                    sb.append(BOUNDARY);
                    sb.append("\r\n");
                    sb.append("Content-Disposition: form-data; name=\"");
                    sb.append(s);
                    sb.append("\"\r\n\r\n");
                    sb.append(params.get(s));
                    sb.append("\r\n");
                }
    
                dos.write(sb.toString().getBytes());
            }

            if (images != null) {
                for (String s : images.keySet()) {
                    File f = images.get(s);
                    sb = new StringBuilder();
                    sb.append("--");
                    sb.append(BOUNDARY);
                    sb.append("\r\n");
                    sb.append("Content-Disposition: form-data; name=\"");
                    sb.append(s);
                    sb.append("\"; filename=\"");
                    sb.append(f.getName());
                    sb.append("\"\r\n");
                    sb.append("Content-Type: application/zip");//这里注意!如果上传的不是图片,要在这里改文件格式,比如txt文件,这里应该是text/plain
                    sb.append("\r\n\r\n");
                    dos.write(sb.toString().getBytes());
    
                    FileInputStream fis = new FileInputStream(f);
                    byte[] buffer = new byte[1024];
                    int len;
                    while ((len = fis.read(buffer)) != -1) {
                        dos.write(buffer, 0, len);
                    }
                    dos.write("\r\n".getBytes());
                    fis.close();
                }
    
                sb = new StringBuilder();
                sb.append("--");
                sb.append(BOUNDARY);
                sb.append("--\r\n");
                dos.write(sb.toString().getBytes());
            }
            dos.flush();

            if (con.getResponseCode() == 200)
                is = con.getInputStream();
            
            dos.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
}

 

  • 0
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
好的,我会尽力回答你的问题。 首先,我们需要了解HTTP协议的基本知识。HTTP协议是一种应用层协议,用于在客户端和服务器之间传输数据。HTTP协议采用请求/响应模型,客户端向服务器发送请求,服务器向客户端返回响应。 下面是一个简单的HTTP请求和响应的示例: 请求: ``` GET /index.html HTTP/1.1 Host: example.com ``` 响应: ``` HTTP/1.1 200 OK Content-Type: text/html Content-Length: 1234 <!DOCTYPE html> <html> <head> <title>Example</title> </head> <body> <h1>Hello World!</h1> </body> </html> ``` 接下来,我们可以使用Java编写一个简单的HTTP服务器程序和HTTP客户端程序,然后使用Apache JMeter对服务器进行性能测试。 HTTP服务器程序: ``` import java.io.*; import java.net.*; public class HTTPServer { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(8080); System.out.println("Server started on port 8080"); while (true) { Socket socket = serverSocket.accept(); System.out.println("Client connected"); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); OutputStream out = socket.getOutputStream(); String request = in.readLine(); System.out.println("Request received: " + request); out.write("HTTP/1.1 200 OK\r\n".getBytes()); out.write("Content-Type: text/html\r\n".getBytes()); out.write("\r\n".getBytes()); out.write("<html><body><h1>Hello World!</h1></body></html>".getBytes()); out.flush(); socket.close(); System.out.println("Client disconnected"); } } } ``` HTTP客户端程序: ``` import java.io.*; import java.net.*; public class HTTPClient { public static void main(String[] args) throws IOException { Socket socket = new Socket("localhost", 8080); OutputStream out = socket.getOutputStream(); out.write("GET / HTTP/1.1\r\n".getBytes()); out.write("Host: localhost\r\n".getBytes()); out.write("\r\n".getBytes()); out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); String response = ""; String line; while ((line = in.readLine()) != null) { response += line + "\n"; } System.out.println(response); socket.close(); } } ``` 这些程序非常简单,HTTP服务器只会返回一个包含“Hello World!”的HTML页面,HTTP客户端会向服务器发送一个GET请求并接收响应。 接下来,我们可以使用Apache JMeter对HTTP服务器进行性能测试。首先,我们需要下载和安装Apache JMeter。安装完成后,打开JMeter,新建一个测试计划,并添加一个线程组和一个HTTP请求。 线程组用于设置模拟用户的数量和持续时间。我们可以设置10个用户同时访问服务器,持续时间为30秒。 HTTP请求用于指定服务器的地址和端口、请求方式和路径。我们可以设置请求方式为GET,路径为“/”,端口为8080。 接下来,我们可以运行测试,并监测响应时间、吞吐量、并发量等指标。根据测试结果,我们可以调整服务器的配置和性能,以提高服务器的性能和稳定性。 为了测试服务器可支持多少个文件同时传输,我们可以在HTTP服务器程序中添加一个文件传输功能。代码如下: ``` import java.io.*; import java.net.*; public class HTTPServer { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(8080); System.out.println("Server started on port 8080"); while (true) { Socket socket = serverSocket.accept(); System.out.println("Client connected"); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); OutputStream out = socket.getOutputStream(); String request = in.readLine(); System.out.println("Request received: " + request); if (request.startsWith("GET /file/")) { String filename = request.substring(10); FileInputStream file = new FileInputStream(filename); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = file.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } file.close(); } else { out.write("HTTP/1.1 200 OK\r\n".getBytes()); out.write("Content-Type: text/html\r\n".getBytes()); out.write("\r\n".getBytes()); out.write("<html><body><h1>Hello World!</h1></body></html>".getBytes()); } out.flush(); socket.close(); System.out.println("Client disconnected"); } } } ``` 这个程序会检查请求是否以“/file/”开头,如果是,则会将指定文件传输给客户端。现在我们可以使用Apache JMeter对服务器进行性能测试,测试可支持多少个文件同时传输。如果服务器配置足够强大,它应该能够同时传输多个文件,而不影响性能。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值