From c56b146509492cf3d27695841f40ccada4b9e255 Mon Sep 17 00:00:00 2001 From: poliakov-alex Date: Mon, 29 Jun 2026 12:19:54 -0400 Subject: [PATCH 1/5] feat(http): add cURL tab to View Results Tree Request panel Render the sampled HTTP request as a ready-to-run curl command in a new "cURL" sub-tab next to Raw and HTTP, so it can be copied to a console or shared. Closes #6375 Co-Authored-By: Claude Opus 4.8 --- .../jmeter/resources/messages.properties | 1 + .../http/visualizers/RequestViewCurl.java | 168 ++++++++++++++++++ .../http/visualizers/RequestViewCurlTest.java | 129 ++++++++++++++ xdocs/changes.xml | 1 + xdocs/usermanual/component_reference.xml | 2 + 5 files changed, 301 insertions(+) create mode 100644 src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/visualizers/RequestViewCurl.java create mode 100644 src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/visualizers/RequestViewCurlTest.java diff --git a/src/core/src/main/resources/org/apache/jmeter/resources/messages.properties b/src/core/src/main/resources/org/apache/jmeter/resources/messages.properties index 3137d879e74..d978a8ed6cc 100644 --- a/src/core/src/main/resources/org/apache/jmeter/resources/messages.properties +++ b/src/core/src/main/resources/org/apache/jmeter/resources/messages.properties @@ -1456,6 +1456,7 @@ view_results_table_request_http_protocol=Protocol view_results_table_request_params_key=Parameter name view_results_table_request_params_value=Value view_results_table_request_raw_nodata=No data to display +view_results_table_request_tab_curl=cURL view_results_table_request_tab_http=HTTP view_results_table_request_tab_raw=Raw view_results_table_result_tab_parsed=Parsed diff --git a/src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/visualizers/RequestViewCurl.java b/src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/visualizers/RequestViewCurl.java new file mode 100644 index 00000000000..a0fb2d37d9c --- /dev/null +++ b/src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/visualizers/RequestViewCurl.java @@ -0,0 +1,168 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jmeter.protocol.http.visualizers; + +import java.awt.BorderLayout; +import java.net.URL; +import java.util.LinkedHashMap; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +import javax.swing.JPanel; + +import org.apache.jmeter.gui.util.JSyntaxSearchToolBar; +import org.apache.jmeter.gui.util.JSyntaxTextArea; +import org.apache.jmeter.gui.util.JTextScrollPane; +import org.apache.jmeter.protocol.http.sampler.HTTPSampleResult; +import org.apache.jmeter.protocol.http.util.HTTPConstants; +import org.apache.jmeter.util.JMeterUtils; +import org.apache.jmeter.visualizers.RequestView; +import org.apache.jorphan.util.StringUtilities; + +import com.google.auto.service.AutoService; + +/** + * Panel that renders an HTTP request as a ready-to-run {@code curl} command, + * so it can be copied and pasted into a console or shared with a developer. + */ +@AutoService(RequestView.class) +public class RequestViewCurl implements RequestView { + + // Used by Request Panel + static final String KEY_LABEL = "view_results_table_request_tab_curl"; //$NON-NLS-1$ + + private static final String NEWLINE = " \\\n"; //$NON-NLS-1$ + + /** + * Headers that must not be reproduced in the curl command: curl generates + * them itself, or they are connection-specific (hop-by-hop) headers that are + * forbidden in HTTP/2 and would make the request fail with a protocol error. + */ + private static final Set SKIPPED_HEADERS = Set.of( + "content-length", //$NON-NLS-1$ + "connection", //$NON-NLS-1$ + "keep-alive", //$NON-NLS-1$ + "proxy-connection", //$NON-NLS-1$ + "transfer-encoding", //$NON-NLS-1$ + "upgrade"); //$NON-NLS-1$ + + private JSyntaxTextArea curlData; + + private JPanel panel; + + @Override + public void init() { + panel = new JPanel(new BorderLayout(0, 5)); + curlData = JSyntaxTextArea.getInstance(20, 80, true); + curlData.setEditable(false); + curlData.setLineWrap(true); + curlData.setWrapStyleWord(true); + panel.add(new JSyntaxSearchToolBar(curlData).getToolBar(), BorderLayout.NORTH); + panel.add(JTextScrollPane.getInstance(curlData), BorderLayout.CENTER); + } + + @Override + public void clearData() { + curlData.setInitialText(""); //$NON-NLS-1$ + } + + @Override + public void setSamplerResult(Object objectResult) { + if (objectResult instanceof HTTPSampleResult sampleResult) { + curlData.setInitialText(buildCurlCommand(sampleResult)); + curlData.setCaretPosition(0); + } else { + // add a message when no http sample (ex. Java request) + curlData.setInitialText(JMeterUtils.getResString("view_results_table_request_http_nohttp")); //$NON-NLS-1$ + } + } + + /** + * Build a {@code curl} command line that reproduces the given HTTP request. + * + * @param sampleResult the sampled HTTP request + * @return the curl command as a string + */ + static String buildCurlCommand(HTTPSampleResult sampleResult) { + StringBuilder sb = new StringBuilder(256); + sb.append("curl"); //$NON-NLS-1$ + + String method = sampleResult.getHTTPMethod(); + if (StringUtilities.isNotBlank(method)) { + sb.append(" -X ").append(quote(method)); //$NON-NLS-1$ + } + + URL url = sampleResult.getURL(); + if (url != null) { + sb.append(NEWLINE).append(" ").append(quote(url.toString())); + } + + boolean hasCookieHeader = false; + String requestHeaders = sampleResult.getRequestHeaders(); + if (StringUtilities.isNotEmpty(requestHeaders)) { + LinkedHashMap headers = JMeterUtils.parseHeaders(requestHeaders); + for (Map.Entry entry : headers.entrySet()) { + String name = entry.getKey(); + if (StringUtilities.isBlank(name) || SKIPPED_HEADERS.contains(name.toLowerCase(Locale.ROOT))) { + continue; + } + if (HTTPConstants.HEADER_COOKIE.equalsIgnoreCase(name)) { + hasCookieHeader = true; + } + sb.append(NEWLINE).append(" -H ").append(quote(name + ": " + entry.getValue())); //$NON-NLS-1$ + } + } + + // Cookies are tracked separately in JMeter; only add them if they were + // not already emitted as a Cookie header above. + String cookies = sampleResult.getCookies(); + if (!hasCookieHeader && StringUtilities.isNotEmpty(cookies)) { + sb.append(NEWLINE).append(" -b ").append(quote(cookies)); //$NON-NLS-1$ + } + + String body = sampleResult.getQueryString(); + if (StringUtilities.isNotBlank(body)) { + sb.append(NEWLINE).append(" --data-raw ").append(quote(body)); //$NON-NLS-1$ + } + + return sb.toString(); + } + + /** + * Wrap a value in single quotes for safe use in a POSIX shell, escaping any + * embedded single quotes using the {@code '\''} idiom. + * + * @param value the value to quote + * @return the shell-quoted value + */ + private static String quote(String value) { + return "'" + value.replace("'", "'\\''") + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + } + + @Override + public JPanel getPanel() { + return panel; + } + + @Override + public String getLabel() { + return JMeterUtils.getResString(KEY_LABEL); + } + +} diff --git a/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/visualizers/RequestViewCurlTest.java b/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/visualizers/RequestViewCurlTest.java new file mode 100644 index 00000000000..4f8270ac5e1 --- /dev/null +++ b/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/visualizers/RequestViewCurlTest.java @@ -0,0 +1,129 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jmeter.protocol.http.visualizers; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.net.MalformedURLException; +import java.net.URL; + +import org.apache.jmeter.protocol.http.sampler.HTTPSampleResult; +import org.junit.jupiter.api.Test; + +class RequestViewCurlTest { + + private static HTTPSampleResult result(String method, String url) throws MalformedURLException { + HTTPSampleResult res = new HTTPSampleResult(); + res.setHTTPMethod(method); + if (url != null) { + res.setURL(new URL(url)); + } + return res; + } + + @Test + void testSimpleGet() throws Exception { + HTTPSampleResult res = result("GET", "http://example.com/path?a=1"); + String curl = RequestViewCurl.buildCurlCommand(res); + + assertTrue(curl.startsWith("curl -X 'GET'"), curl); + assertTrue(curl.contains("'http://example.com/path?a=1'"), curl); + assertFalse(curl.contains("--data-raw"), curl); + } + + @Test + void testHeadersAreEmitted() throws Exception { + HTTPSampleResult res = result("GET", "http://example.com/"); + res.setRequestHeaders("Accept: application/json\nUser-Agent: JMeter"); + String curl = RequestViewCurl.buildCurlCommand(res); + + assertTrue(curl.contains("-H 'Accept: application/json'"), curl); + assertTrue(curl.contains("-H 'User-Agent: JMeter'"), curl); + } + + @Test + void testPostBody() throws Exception { + HTTPSampleResult res = result("POST", "http://example.com/submit"); + res.setRequestHeaders("Content-Type: application/json"); + res.setQueryString("{\"name\":\"value\"}"); + String curl = RequestViewCurl.buildCurlCommand(res); + + assertTrue(curl.contains("-X 'POST'"), curl); + assertTrue(curl.contains("--data-raw '{\"name\":\"value\"}'"), curl); + } + + @Test + void testConnectionAndAutoHeadersAreSkipped() throws Exception { + HTTPSampleResult res = result("POST", "https://example.com/"); + res.setRequestHeaders("Connection: keep-alive\n" + + "Content-Length: 140\n" + + "Transfer-Encoding: chunked\n" + + "Content-Type: application/json\n" + + "Accept: application/json"); + res.setQueryString("{}"); + String curl = RequestViewCurl.buildCurlCommand(res); + + // curl manages these / they are forbidden in HTTP/2, so they must be dropped + assertFalse(curl.contains("Connection"), curl); + assertFalse(curl.contains("Content-Length"), curl); + assertFalse(curl.contains("Transfer-Encoding"), curl); + // genuine request headers are still kept + assertTrue(curl.contains("-H 'Content-Type: application/json'"), curl); + assertTrue(curl.contains("-H 'Accept: application/json'"), curl); + } + + @Test + void testCookiesAddedAsFlag() throws Exception { + HTTPSampleResult res = result("GET", "http://example.com/"); + res.setCookies("session=abc; theme=dark"); + String curl = RequestViewCurl.buildCurlCommand(res); + + assertTrue(curl.contains("-b 'session=abc; theme=dark'"), curl); + } + + @Test + void testCookieHeaderNotDuplicated() throws Exception { + HTTPSampleResult res = result("GET", "http://example.com/"); + res.setRequestHeaders("Cookie: session=abc"); + res.setCookies("session=abc"); + String curl = RequestViewCurl.buildCurlCommand(res); + + assertTrue(curl.contains("-H 'Cookie: session=abc'"), curl); + assertFalse(curl.contains("-b "), curl); + } + + @Test + void testSingleQuoteIsEscaped() throws Exception { + HTTPSampleResult res = result("POST", "http://example.com/"); + res.setQueryString("name=O'Brien"); + String curl = RequestViewCurl.buildCurlCommand(res); + + // single quote becomes '\'' so the value stays shell-safe + assertTrue(curl.contains("--data-raw 'name=O'\\''Brien'"), curl); + } + + @Test + void testNullUrlDoesNotFail() throws Exception { + HTTPSampleResult res = result("GET", null); + String curl = RequestViewCurl.buildCurlCommand(res); + + assertEquals("curl -X 'GET'", curl); + } +} diff --git a/xdocs/changes.xml b/xdocs/changes.xml index 988377c81b1..7a879c7264e 100644 --- a/xdocs/changes.xml +++ b/xdocs/changes.xml @@ -104,6 +104,7 @@ Summary
  • 6333Apply HiDPI mode automatically when setting up the GUI so JMeter looks sharp on high-resolution displays. Contributed by Gabriele Coletta (github.com/gdmg92)
  • 6656Replace the previous feather icon with the new oak leaf in the JMeter logo.
  • +
  • 6375Add a cURL tab to the Request panel in View Results Tree, showing the sampled HTTP request as a ready-to-run curl command that can be copied to a console. Contributed by Oleksandr Poliakov (github.com/poliakov-alex)
Bug fixes diff --git a/xdocs/usermanual/component_reference.xml b/xdocs/usermanual/component_reference.xml index 663b24fe6e4..17e0616c316 100644 --- a/xdocs/usermanual/component_reference.xml +++ b/xdocs/usermanual/component_reference.xml @@ -2798,6 +2798,8 @@ response for any sample. In addition to showing the response, you can see the t this response, and some response codes. Note that the Request panel only shows the headers added by JMeter. It does not show any headers (such as Host) that may be added by the HTTP protocol implementation. +For HTTP samples the Request panel also provides a cURL tab that renders the request as a +ready-to-run curl command, so it can be copied to a console or shared with a developer.

There are several ways to view the response, selectable by a drop-down box at the bottom of the left hand panel.

From f4ab34e16885bae4321328095be29a215f9aec74 Mon Sep 17 00:00:00 2001 From: poliakov-alex Date: Mon, 27 Jul 2026 11:52:47 -0400 Subject: [PATCH 2/5] PR #6736 edits based on comments from code review --- .../jmeter/resources/messages.properties | 1 + .../http/curl/CurlCommandFormatter.java | 261 ++++++++++++++++++ .../http/visualizers/RequestViewCurl.java | 89 +----- .../http/curl/CurlCommandFormatterTest.java | 239 ++++++++++++++++ .../http/visualizers/RequestViewCurlTest.java | 129 --------- xdocs/changes.xml | 2 +- xdocs/usermanual/component_reference.xml | 7 + 7 files changed, 513 insertions(+), 215 deletions(-) create mode 100644 src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatter.java create mode 100644 src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatterTest.java delete mode 100644 src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/visualizers/RequestViewCurlTest.java diff --git a/src/core/src/main/resources/org/apache/jmeter/resources/messages.properties b/src/core/src/main/resources/org/apache/jmeter/resources/messages.properties index d978a8ed6cc..dd04c9bc8b4 100644 --- a/src/core/src/main/resources/org/apache/jmeter/resources/messages.properties +++ b/src/core/src/main/resources/org/apache/jmeter/resources/messages.properties @@ -1457,6 +1457,7 @@ view_results_table_request_params_key=Parameter name view_results_table_request_params_value=Value view_results_table_request_raw_nodata=No data to display view_results_table_request_tab_curl=cURL +view_results_table_request_tab_curl_body_omitted=Request body not shown (file sent as body or non-repeatable content) and cannot be reproduced view_results_table_request_tab_http=HTTP view_results_table_request_tab_raw=Raw view_results_table_result_tab_parsed=Parsed diff --git a/src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatter.java b/src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatter.java new file mode 100644 index 00000000000..ed64caaddab --- /dev/null +++ b/src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatter.java @@ -0,0 +1,261 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jmeter.protocol.http.curl; + +import java.net.URL; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Set; + +import org.apache.jmeter.config.Argument; +import org.apache.jmeter.protocol.http.config.MultipartUrlConfig; +import org.apache.jmeter.protocol.http.sampler.HTTPSampleResult; +import org.apache.jmeter.protocol.http.util.HTTPConstants; +import org.apache.jmeter.protocol.http.util.HTTPFileArg; +import org.apache.jmeter.testelement.property.JMeterProperty; +import org.apache.jmeter.util.JMeterUtils; +import org.apache.jorphan.util.StringUtilities; + +/** + * Renders an {@link HTTPSampleResult} as a ready-to-run {@code curl} command, + * the reverse of what {@link BasicCurlParser} does. + * + *

The generated command targets a POSIX-compatible shell: arguments are + * single-quoted and lines are continued with a trailing backslash. It is not + * valid {@code cmd.exe} or PowerShell syntax.

+ * + *

The class has no Swing dependency so it can be reused outside the + * View Results Tree (for example by a future "Copy as cURL" sampler action).

+ */ +public final class CurlCommandFormatter { + + /** Backslash line continuation followed by indentation, for a POSIX shell. */ + private static final String NEWLINE = " \\\n "; //$NON-NLS-1$ + + private static final String ACCEPT_ENCODING = "accept-encoding"; //$NON-NLS-1$ + + private static final String BOUNDARY = "boundary="; //$NON-NLS-1$ + + /** + * Headers that must not be reproduced in the curl command: curl generates + * them itself, they are connection-specific (hop-by-hop) headers that are + * forbidden in HTTP/2 and would make the request fail with a protocol + * error, or they are pseudo-headers JMeter adds only for reporting and that + * never went on the wire (X-LocalAddress). + */ + private static final Set SKIPPED_HEADERS = Set.of( + "content-length", //$NON-NLS-1$ + "connection", //$NON-NLS-1$ + "keep-alive", //$NON-NLS-1$ + "proxy-connection", //$NON-NLS-1$ + "transfer-encoding", //$NON-NLS-1$ + "upgrade", //$NON-NLS-1$ + HTTPConstants.HEADER_LOCAL_ADDRESS.toLowerCase(Locale.ROOT)); + + /** + * Markers JMeter writes into the rendered request body in place of content + * it did not keep (a file sent as the body, or a non-repeatable entity). + * When present, the body is not the real wire body and cannot be reproduced. + * + * @see org.apache.jmeter.protocol.http.sampler.PostWriter + */ + private static final String[] BODY_PLACEHOLDERS = { + "", //$NON-NLS-1$ + "" //$NON-NLS-1$ + }; + + private CurlCommandFormatter() { + } + + /** + * Build a {@code curl} command line that reproduces the given HTTP request. + * + * @param sampleResult the sampled HTTP request + * @return the curl command as a string + */ + public static String format(HTTPSampleResult sampleResult) { + StringBuilder sb = new StringBuilder(256); + sb.append("curl"); //$NON-NLS-1$ + + String method = sampleResult.getHTTPMethod(); + boolean isHead = HTTPConstants.HEAD.equalsIgnoreCase(method); + boolean isGet = StringUtilities.isBlank(method) || HTTPConstants.GET.equalsIgnoreCase(method); + + // Split by line (not via JMeterUtils.parseHeaders) so repeated header + // names such as several Accept values are all preserved. + List headers = new ArrayList<>(); + String contentType = null; + boolean acceptsEncoding = false; + String requestHeaders = sampleResult.getRequestHeaders(); + if (StringUtilities.isNotEmpty(requestHeaders)) { + for (String header : requestHeaders.split("\n")) { //$NON-NLS-1$ + int colon = header.indexOf(':'); + if (colon <= 0) { + continue; + } + String name = header.substring(0, colon).trim(); + String value = header.substring(colon + 1).trim(); + String lower = name.toLowerCase(Locale.ROOT); + if (SKIPPED_HEADERS.contains(lower)) { + continue; + } + if (HTTPConstants.HEADER_CONTENT_TYPE.equalsIgnoreCase(name)) { + contentType = value; + } + if (ACCEPT_ENCODING.equals(lower)) { + acceptsEncoding = true; + } + headers.add(new String[] { name, value }); + } + } + + String body = isHead ? "" : sampleResult.getQueryString(); //$NON-NLS-1$ + boolean hasBody = StringUtilities.isNotEmpty(body); + boolean isMultipart = contentType != null + && contentType.toLowerCase(Locale.ROOT).startsWith(HTTPConstants.MULTIPART_FORM_DATA); + // Multipart bodies are rebuilt as -F flags; curl then sets its own + // Content-Type (with its own boundary), so the original one is dropped. + List formParts = hasBody && isMultipart ? parseMultipartForm(contentType, body) : List.of(); + boolean emitsForm = !formParts.isEmpty(); + boolean emitsDataRaw = hasBody && !isMultipart && !containsPlaceholder(body); + + // Method: --head for HEAD (plain "-X HEAD" makes curl wait for a body it + // never gets); no -X for a plain GET; -X GET only when a GET carries a + // raw body, otherwise curl would switch it to POST; -X for everything else. + if (isHead) { + sb.append(" --head"); //$NON-NLS-1$ + } else if (!isGet) { + sb.append(" -X ").append(quote(method)); //$NON-NLS-1$ + } else if (emitsDataRaw) { + sb.append(" -X ").append(quote(HTTPConstants.GET)); //$NON-NLS-1$ + } + + URL url = sampleResult.getURL(); + if (url != null) { + sb.append(NEWLINE).append(quote(url.toString())); + } + + for (String[] header : headers) { + if (emitsForm && HTTPConstants.HEADER_CONTENT_TYPE.equalsIgnoreCase(header[0])) { + continue; + } + sb.append(NEWLINE).append("-H ").append(quote(header[0] + ": " + header[1])); //$NON-NLS-1$ //$NON-NLS-2$ + } + + // HttpClient disables automatic decompression, so Accept-Encoding is only + // present when explicitly set; --compressed makes curl decode the response. + if (acceptsEncoding) { + sb.append(NEWLINE).append("--compressed"); //$NON-NLS-1$ + } + + String cookies = sampleResult.getCookies(); + if (StringUtilities.isNotEmpty(cookies)) { + sb.append(NEWLINE).append("-b ").append(quote(cookies)); //$NON-NLS-1$ + } + + if (emitsForm) { + for (String part : formParts) { + sb.append(NEWLINE).append("-F ").append(quote(part)); //$NON-NLS-1$ + } + } else if (emitsDataRaw) { + sb.append(NEWLINE).append("--data-raw ").append(quote(body)); //$NON-NLS-1$ + } else if (hasBody) { + // A file sent as the body or a non-repeatable entity: the bytes were + // not kept, so emitting them would produce a silently-wrong command. + sb.append('\n').append("# ") //$NON-NLS-1$ + .append(JMeterUtils.getResString("view_results_table_request_tab_curl_body_omitted")); //$NON-NLS-1$ + } + + return sb.toString(); + } + + /** + * Rebuild the {@code -F} form parts of a multipart request from its rendered + * body. Regular fields become {@code name=value}; file parts become + * {@code name=@filename;type=...}. JMeter does not keep the uploaded bytes, + * so the file name is only a placeholder the user edits to a real path + * before running the command. + * + * @return the form parts, or an empty list if the body cannot be parsed + */ + private static List parseMultipartForm(String contentType, String body) { + String boundary = extractBoundary(contentType); + if (StringUtilities.isBlank(boundary)) { + return List.of(); + } + MultipartUrlConfig multipart = new MultipartUrlConfig(boundary); + try { + multipart.parseArguments(body); + } catch (RuntimeException e) { // NOSONAR malformed body: fall back to the omitted-body note + return List.of(); + } + List parts = new ArrayList<>(); + for (JMeterProperty property : multipart.getArguments()) { + Argument argument = (Argument) property.getObjectValue(); + parts.add(argument.getName() + "=" + argument.getValue()); //$NON-NLS-1$ + } + for (HTTPFileArg file : multipart.getHTTPFileArgs().asArray()) { + StringBuilder part = new StringBuilder(); + part.append(file.getParamName()).append("=@").append(file.getPath()); //$NON-NLS-1$ + if (StringUtilities.isNotEmpty(file.getMimeType())) { + part.append(";type=").append(file.getMimeType()); //$NON-NLS-1$ + } + parts.add(part.toString()); + } + return parts; + } + + /** + * @return the {@code boundary} value of a multipart content type, or + * {@code null} if it is absent + */ + private static String extractBoundary(String contentType) { + int index = contentType.toLowerCase(Locale.ROOT).indexOf(BOUNDARY); + if (index < 0) { + return null; + } + String boundary = contentType.substring(index + BOUNDARY.length()); + int semicolon = boundary.indexOf(';'); + if (semicolon >= 0) { + boundary = boundary.substring(0, semicolon); + } + return boundary.trim(); + } + + private static boolean containsPlaceholder(String body) { + for (String placeholder : BODY_PLACEHOLDERS) { + if (body.contains(placeholder)) { + return true; + } + } + return false; + } + + /** + * Wrap a value in single quotes for safe use in a POSIX shell, escaping any + * embedded single quotes using the {@code '\''} idiom. + * + * @param value the value to quote + * @return the shell-quoted value + */ + private static String quote(String value) { + return "'" + value.replace("'", "'\\''") + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + } + +} diff --git a/src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/visualizers/RequestViewCurl.java b/src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/visualizers/RequestViewCurl.java index a0fb2d37d9c..270e6e70081 100644 --- a/src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/visualizers/RequestViewCurl.java +++ b/src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/visualizers/RequestViewCurl.java @@ -18,28 +18,24 @@ package org.apache.jmeter.protocol.http.visualizers; import java.awt.BorderLayout; -import java.net.URL; -import java.util.LinkedHashMap; -import java.util.Locale; -import java.util.Map; -import java.util.Set; import javax.swing.JPanel; import org.apache.jmeter.gui.util.JSyntaxSearchToolBar; import org.apache.jmeter.gui.util.JSyntaxTextArea; import org.apache.jmeter.gui.util.JTextScrollPane; +import org.apache.jmeter.protocol.http.curl.CurlCommandFormatter; import org.apache.jmeter.protocol.http.sampler.HTTPSampleResult; -import org.apache.jmeter.protocol.http.util.HTTPConstants; import org.apache.jmeter.util.JMeterUtils; import org.apache.jmeter.visualizers.RequestView; -import org.apache.jorphan.util.StringUtilities; import com.google.auto.service.AutoService; /** * Panel that renders an HTTP request as a ready-to-run {@code curl} command, * so it can be copied and pasted into a console or shared with a developer. + * + * @see CurlCommandFormatter */ @AutoService(RequestView.class) public class RequestViewCurl implements RequestView { @@ -47,21 +43,6 @@ public class RequestViewCurl implements RequestView { // Used by Request Panel static final String KEY_LABEL = "view_results_table_request_tab_curl"; //$NON-NLS-1$ - private static final String NEWLINE = " \\\n"; //$NON-NLS-1$ - - /** - * Headers that must not be reproduced in the curl command: curl generates - * them itself, or they are connection-specific (hop-by-hop) headers that are - * forbidden in HTTP/2 and would make the request fail with a protocol error. - */ - private static final Set SKIPPED_HEADERS = Set.of( - "content-length", //$NON-NLS-1$ - "connection", //$NON-NLS-1$ - "keep-alive", //$NON-NLS-1$ - "proxy-connection", //$NON-NLS-1$ - "transfer-encoding", //$NON-NLS-1$ - "upgrade"); //$NON-NLS-1$ - private JSyntaxTextArea curlData; private JPanel panel; @@ -85,7 +66,7 @@ public void clearData() { @Override public void setSamplerResult(Object objectResult) { if (objectResult instanceof HTTPSampleResult sampleResult) { - curlData.setInitialText(buildCurlCommand(sampleResult)); + curlData.setInitialText(CurlCommandFormatter.format(sampleResult)); curlData.setCaretPosition(0); } else { // add a message when no http sample (ex. Java request) @@ -93,68 +74,6 @@ public void setSamplerResult(Object objectResult) { } } - /** - * Build a {@code curl} command line that reproduces the given HTTP request. - * - * @param sampleResult the sampled HTTP request - * @return the curl command as a string - */ - static String buildCurlCommand(HTTPSampleResult sampleResult) { - StringBuilder sb = new StringBuilder(256); - sb.append("curl"); //$NON-NLS-1$ - - String method = sampleResult.getHTTPMethod(); - if (StringUtilities.isNotBlank(method)) { - sb.append(" -X ").append(quote(method)); //$NON-NLS-1$ - } - - URL url = sampleResult.getURL(); - if (url != null) { - sb.append(NEWLINE).append(" ").append(quote(url.toString())); - } - - boolean hasCookieHeader = false; - String requestHeaders = sampleResult.getRequestHeaders(); - if (StringUtilities.isNotEmpty(requestHeaders)) { - LinkedHashMap headers = JMeterUtils.parseHeaders(requestHeaders); - for (Map.Entry entry : headers.entrySet()) { - String name = entry.getKey(); - if (StringUtilities.isBlank(name) || SKIPPED_HEADERS.contains(name.toLowerCase(Locale.ROOT))) { - continue; - } - if (HTTPConstants.HEADER_COOKIE.equalsIgnoreCase(name)) { - hasCookieHeader = true; - } - sb.append(NEWLINE).append(" -H ").append(quote(name + ": " + entry.getValue())); //$NON-NLS-1$ - } - } - - // Cookies are tracked separately in JMeter; only add them if they were - // not already emitted as a Cookie header above. - String cookies = sampleResult.getCookies(); - if (!hasCookieHeader && StringUtilities.isNotEmpty(cookies)) { - sb.append(NEWLINE).append(" -b ").append(quote(cookies)); //$NON-NLS-1$ - } - - String body = sampleResult.getQueryString(); - if (StringUtilities.isNotBlank(body)) { - sb.append(NEWLINE).append(" --data-raw ").append(quote(body)); //$NON-NLS-1$ - } - - return sb.toString(); - } - - /** - * Wrap a value in single quotes for safe use in a POSIX shell, escaping any - * embedded single quotes using the {@code '\''} idiom. - * - * @param value the value to quote - * @return the shell-quoted value - */ - private static String quote(String value) { - return "'" + value.replace("'", "'\\''") + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - } - @Override public JPanel getPanel() { return panel; diff --git a/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatterTest.java b/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatterTest.java new file mode 100644 index 00000000000..406013b259d --- /dev/null +++ b/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatterTest.java @@ -0,0 +1,239 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jmeter.protocol.http.curl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.apache.jmeter.protocol.http.sampler.HTTPSampleResult; +import org.junit.jupiter.api.Test; + +class CurlCommandFormatterTest { + + private static HTTPSampleResult result(String method, String url) throws MalformedURLException { + HTTPSampleResult res = new HTTPSampleResult(); + res.setHTTPMethod(method); + if (url != null) { + res.setURL(new URL(url)); + } + return res; + } + + @Test + void testSimpleGetOmitsMethodFlag() throws Exception { + HTTPSampleResult res = result("GET", "http://example.com/path?a=1"); + + assertEquals( + "curl \\\n 'http://example.com/path?a=1'", + CurlCommandFormatter.format(res)); + } + + @Test + void testPostWithHeaderAndBody() throws Exception { + HTTPSampleResult res = result("POST", "http://example.com/submit"); + res.setRequestHeaders("Content-Type: application/json"); + res.setQueryString("{\"name\":\"value\"}"); + + assertEquals( + "curl -X 'POST' \\\n" + + " 'http://example.com/submit' \\\n" + + " -H 'Content-Type: application/json' \\\n" + + " --data-raw '{\"name\":\"value\"}'", + CurlCommandFormatter.format(res)); + } + + @Test + void testRepeatedHeadersArePreserved() throws Exception { + HTTPSampleResult res = result("GET", "http://example.com/"); + res.setRequestHeaders("X-Trace: a\nX-Trace: b\nAccept: text/html\nAccept: application/json"); + + assertEquals( + "curl \\\n" + + " 'http://example.com/' \\\n" + + " -H 'X-Trace: a' \\\n" + + " -H 'X-Trace: b' \\\n" + + " -H 'Accept: text/html' \\\n" + + " -H 'Accept: application/json'", + CurlCommandFormatter.format(res)); + } + + @Test + void testConnectionAutoAndPseudoHeadersAreSkipped() throws Exception { + HTTPSampleResult res = result("POST", "http://example.com/"); + res.setRequestHeaders("Connection: keep-alive\n" + + "Content-Length: 5\n" + + "Transfer-Encoding: chunked\n" + + "X-LocalAddress: /10.0.0.5\n" + + "Accept: application/json"); + res.setQueryString("hello"); + + assertEquals( + "curl -X 'POST' \\\n" + + " 'http://example.com/' \\\n" + + " -H 'Accept: application/json' \\\n" + + " --data-raw 'hello'", + CurlCommandFormatter.format(res)); + } + + @Test + void testHeadUsesHeadFlag() throws Exception { + HTTPSampleResult res = result("HEAD", "http://example.com/"); + res.setRequestHeaders("Accept: */*"); + + String curl = CurlCommandFormatter.format(res); + assertTrue(curl.startsWith("curl --head "), curl); + assertFalse(curl.contains("-X "), curl); + assertFalse(curl.contains("--data"), curl); + } + + @Test + void testGetWithBodyKeepsMethodSoCurlDoesNotSwitchToPost() throws Exception { + HTTPSampleResult res = result("GET", "http://example.com/"); + res.setQueryString("q=1"); + + String curl = CurlCommandFormatter.format(res); + assertTrue(curl.contains("-X 'GET'"), curl); + assertTrue(curl.contains("--data-raw 'q=1'"), curl); + } + + @Test + void testMultipartRebuiltAsFormFlagsWithFileName() throws Exception { + HTTPSampleResult res = result("POST", "http://example.com/upload"); + res.setRequestHeaders("Content-Type: multipart/form-data; boundary=xyz"); + // Rendered multipart body as JMeter stores it in the result. + res.setQueryString("--xyz\r\n" + + "Content-Disposition: form-data; name=\"comment\"\r\n" + + "\r\n" + + "hello\r\n" + + "--xyz\r\n" + + "Content-Disposition: form-data; name=\"upload\"; filename=\"report.pdf\"\r\n" + + "Content-Type: application/pdf\r\n" + + "\r\n" + + "\r\n" + + "--xyz--\r\n"); + + String curl = CurlCommandFormatter.format(res); + // The file part is rebuilt with the file name as an editable @placeholder. + assertTrue(curl.contains("-F 'upload=@report.pdf;type=application/pdf'"), curl); + assertTrue(curl.contains("-F 'comment=hello'"), curl); + // No raw dump of the placeholder, and curl sets its own multipart Content-Type. + assertFalse(curl.contains("--data-raw"), curl); + assertFalse(curl.contains("actual file content"), curl); + assertFalse(curl.contains("-H 'Content-Type: multipart/form-data"), curl); + } + + @Test + void testFileAsBodyPlaceholderIsNotReproduced() throws Exception { + HTTPSampleResult res = result("POST", "http://example.com/upload"); + res.setRequestHeaders("Content-Type: application/octet-stream"); + res.setQueryString(""); + + String curl = CurlCommandFormatter.format(res); + assertFalse(curl.contains("--data-raw"), curl); + } + + @Test + void testNonRepeatableBodyPlaceholderIsNotReproduced() throws Exception { + HTTPSampleResult res = result("POST", "http://example.com/"); + res.setQueryString(""); + + String curl = CurlCommandFormatter.format(res); + assertFalse(curl.contains("--data-raw"), curl); + } + + @Test + void testWhitespaceOnlyBodyIsKept() throws Exception { + HTTPSampleResult res = result("POST", "http://example.com/"); + res.setQueryString(" "); + + assertTrue(CurlCommandFormatter.format(res).contains("--data-raw ' '")); + } + + @Test + void testCookiesAddedAsFlag() throws Exception { + HTTPSampleResult res = result("GET", "http://example.com/"); + res.setCookies("session=abc; theme=dark"); + + assertTrue(CurlCommandFormatter.format(res).contains("-b 'session=abc; theme=dark'")); + } + + @Test + void testAcceptEncodingAddsCompressed() throws Exception { + HTTPSampleResult res = result("GET", "http://example.com/"); + res.setRequestHeaders("Accept-Encoding: gzip, deflate"); + + String curl = CurlCommandFormatter.format(res); + assertTrue(curl.contains("--compressed"), curl); + assertTrue(curl.contains("-H 'Accept-Encoding: gzip, deflate'"), curl); + } + + @Test + void testSingleQuoteIsEscaped() throws Exception { + HTTPSampleResult res = result("POST", "http://example.com/"); + res.setQueryString("name=O'Brien"); + + // single quote becomes '\'' so the value stays shell-safe + assertTrue(CurlCommandFormatter.format(res).contains("--data-raw 'name=O'\\''Brien'")); + } + + @Test + void testNullUrlDoesNotFail() throws Exception { + HTTPSampleResult res = result("GET", null); + + assertEquals("curl", CurlCommandFormatter.format(res)); + } + + @Test + void testRoundTripThroughParser() throws Exception { + HTTPSampleResult res = result("POST", "http://example.com/submit"); + res.setRequestHeaders("X-A: 1\nX-B: 2"); + res.setQueryString("payload"); + + String curl = CurlCommandFormatter.format(res); + BasicCurlParser.Request parsed = new BasicCurlParser().parse(curl); + + assertEquals("POST", parsed.getMethod()); + assertEquals("http://example.com/submit", parsed.getUrl()); + assertEquals("payload", parsed.getPostData()); + List headers = parsed.getHeaders().stream() + .map(e -> e.getKey() + ": " + e.getValue()) + .collect(Collectors.toList()); + assertEquals(List.of("X-A: 1", "X-B: 2"), headers); + } + + @Test + void testRoundTripPreservesDuplicateHeaders() throws Exception { + HTTPSampleResult res = result("POST", "http://example.com/"); + res.setRequestHeaders("Accept: text/html\nAccept: application/json"); + res.setQueryString("x"); + + BasicCurlParser.Request parsed = new BasicCurlParser().parse(CurlCommandFormatter.format(res)); + List accept = parsed.getHeaders().stream() + .filter(e -> "Accept".equals(e.getKey())) + .map(Map.Entry::getValue) + .collect(Collectors.toList()); + assertEquals(List.of("text/html", "application/json"), accept); + } +} diff --git a/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/visualizers/RequestViewCurlTest.java b/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/visualizers/RequestViewCurlTest.java deleted file mode 100644 index 4f8270ac5e1..00000000000 --- a/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/visualizers/RequestViewCurlTest.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to you under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.jmeter.protocol.http.visualizers; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.net.MalformedURLException; -import java.net.URL; - -import org.apache.jmeter.protocol.http.sampler.HTTPSampleResult; -import org.junit.jupiter.api.Test; - -class RequestViewCurlTest { - - private static HTTPSampleResult result(String method, String url) throws MalformedURLException { - HTTPSampleResult res = new HTTPSampleResult(); - res.setHTTPMethod(method); - if (url != null) { - res.setURL(new URL(url)); - } - return res; - } - - @Test - void testSimpleGet() throws Exception { - HTTPSampleResult res = result("GET", "http://example.com/path?a=1"); - String curl = RequestViewCurl.buildCurlCommand(res); - - assertTrue(curl.startsWith("curl -X 'GET'"), curl); - assertTrue(curl.contains("'http://example.com/path?a=1'"), curl); - assertFalse(curl.contains("--data-raw"), curl); - } - - @Test - void testHeadersAreEmitted() throws Exception { - HTTPSampleResult res = result("GET", "http://example.com/"); - res.setRequestHeaders("Accept: application/json\nUser-Agent: JMeter"); - String curl = RequestViewCurl.buildCurlCommand(res); - - assertTrue(curl.contains("-H 'Accept: application/json'"), curl); - assertTrue(curl.contains("-H 'User-Agent: JMeter'"), curl); - } - - @Test - void testPostBody() throws Exception { - HTTPSampleResult res = result("POST", "http://example.com/submit"); - res.setRequestHeaders("Content-Type: application/json"); - res.setQueryString("{\"name\":\"value\"}"); - String curl = RequestViewCurl.buildCurlCommand(res); - - assertTrue(curl.contains("-X 'POST'"), curl); - assertTrue(curl.contains("--data-raw '{\"name\":\"value\"}'"), curl); - } - - @Test - void testConnectionAndAutoHeadersAreSkipped() throws Exception { - HTTPSampleResult res = result("POST", "https://example.com/"); - res.setRequestHeaders("Connection: keep-alive\n" - + "Content-Length: 140\n" - + "Transfer-Encoding: chunked\n" - + "Content-Type: application/json\n" - + "Accept: application/json"); - res.setQueryString("{}"); - String curl = RequestViewCurl.buildCurlCommand(res); - - // curl manages these / they are forbidden in HTTP/2, so they must be dropped - assertFalse(curl.contains("Connection"), curl); - assertFalse(curl.contains("Content-Length"), curl); - assertFalse(curl.contains("Transfer-Encoding"), curl); - // genuine request headers are still kept - assertTrue(curl.contains("-H 'Content-Type: application/json'"), curl); - assertTrue(curl.contains("-H 'Accept: application/json'"), curl); - } - - @Test - void testCookiesAddedAsFlag() throws Exception { - HTTPSampleResult res = result("GET", "http://example.com/"); - res.setCookies("session=abc; theme=dark"); - String curl = RequestViewCurl.buildCurlCommand(res); - - assertTrue(curl.contains("-b 'session=abc; theme=dark'"), curl); - } - - @Test - void testCookieHeaderNotDuplicated() throws Exception { - HTTPSampleResult res = result("GET", "http://example.com/"); - res.setRequestHeaders("Cookie: session=abc"); - res.setCookies("session=abc"); - String curl = RequestViewCurl.buildCurlCommand(res); - - assertTrue(curl.contains("-H 'Cookie: session=abc'"), curl); - assertFalse(curl.contains("-b "), curl); - } - - @Test - void testSingleQuoteIsEscaped() throws Exception { - HTTPSampleResult res = result("POST", "http://example.com/"); - res.setQueryString("name=O'Brien"); - String curl = RequestViewCurl.buildCurlCommand(res); - - // single quote becomes '\'' so the value stays shell-safe - assertTrue(curl.contains("--data-raw 'name=O'\\''Brien'"), curl); - } - - @Test - void testNullUrlDoesNotFail() throws Exception { - HTTPSampleResult res = result("GET", null); - String curl = RequestViewCurl.buildCurlCommand(res); - - assertEquals("curl -X 'GET'", curl); - } -} diff --git a/xdocs/changes.xml b/xdocs/changes.xml index 7a879c7264e..9353cc0420c 100644 --- a/xdocs/changes.xml +++ b/xdocs/changes.xml @@ -81,6 +81,7 @@ Summary
  • 6250Avoid adding "; charset=" automatically to multipart/form-data requests to align behavior with modern HTTP clients.
  • 6080Preserve the original HTTP method when following 307 and 308 redirects according to the HTTP specification. Contributed by LeeJiWon (github.com/dlwldnjs1009)
  • 62676268Add a space between key and value after : in View Results Tree > Sampler result tab for better readability.
  • +
  • 63756736Add a cURL tab to the Request panel in View Results Tree, showing the sampled HTTP request as a ready-to-run curl command that can be copied to a console or shared with a developer. Contributed by Oleksandr Poliakov (github.com/poliakov-alex)
  • Timers, Assertions, Config, Pre- & Post-Processors

    @@ -104,7 +105,6 @@ Summary
    • 6333Apply HiDPI mode automatically when setting up the GUI so JMeter looks sharp on high-resolution displays. Contributed by Gabriele Coletta (github.com/gdmg92)
    • 6656Replace the previous feather icon with the new oak leaf in the JMeter logo.
    • -
    • 6375Add a cURL tab to the Request panel in View Results Tree, showing the sampled HTTP request as a ready-to-run curl command that can be copied to a console. Contributed by Oleksandr Poliakov (github.com/poliakov-alex)
    Bug fixes diff --git a/xdocs/usermanual/component_reference.xml b/xdocs/usermanual/component_reference.xml index 17e0616c316..abcdf241699 100644 --- a/xdocs/usermanual/component_reference.xml +++ b/xdocs/usermanual/component_reference.xml @@ -2798,8 +2798,15 @@ response for any sample. In addition to showing the response, you can see the t this response, and some response codes. Note that the Request panel only shows the headers added by JMeter. It does not show any headers (such as Host) that may be added by the HTTP protocol implementation. +

    For HTTP samples the Request panel also provides a cURL tab that renders the request as a ready-to-run curl command, so it can be copied to a console or shared with a developer. +The command targets a POSIX-compatible shell (it is not valid cmd.exe or PowerShell syntax). +It reproduces whatever the sample carried, including Authorization headers, cookies and API keys, +so treat it as sensitive when sharing. Multipart uploads are rendered as -F form parts using the +original field and file names; since JMeter does not keep the uploaded bytes, a file is referenced as +@filename, a placeholder to edit to a real path before running the command. A file sent as the +whole request body, or a non-repeatable body, cannot be shown at all and is omitted with a note.

    There are several ways to view the response, selectable by a drop-down box at the bottom of the left hand panel.

    From 56385fe87050b6a66a61450296a8235dc8477204 Mon Sep 17 00:00:00 2001 From: poliakov-alex Date: Wed, 29 Jul 2026 11:28:32 -0400 Subject: [PATCH 3/5] PR #6736 edits based on comments from code review. Part 2 --- .../http/curl/CurlCommandFormatter.java | 30 +++++++++++-------- .../http/curl/CurlCommandFormatterTest.java | 22 ++++++++++++-- xdocs/usermanual/component_reference.xml | 2 +- 3 files changed, 39 insertions(+), 15 deletions(-) diff --git a/src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatter.java b/src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatter.java index ed64caaddab..19d02237b4c 100644 --- a/src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatter.java +++ b/src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatter.java @@ -48,7 +48,7 @@ public final class CurlCommandFormatter { /** Backslash line continuation followed by indentation, for a POSIX shell. */ private static final String NEWLINE = " \\\n "; //$NON-NLS-1$ - private static final String ACCEPT_ENCODING = "accept-encoding"; //$NON-NLS-1$ + private static final String ACCEPT_ENCODING = "Accept-Encoding"; //$NON-NLS-1$ private static final String BOUNDARY = "boundary="; //$NON-NLS-1$ @@ -118,7 +118,7 @@ public static String format(HTTPSampleResult sampleResult) { if (HTTPConstants.HEADER_CONTENT_TYPE.equalsIgnoreCase(name)) { contentType = value; } - if (ACCEPT_ENCODING.equals(lower)) { + if (ACCEPT_ENCODING.equalsIgnoreCase(name)) { acceptsEncoding = true; } headers.add(new String[] { name, value }); @@ -131,7 +131,7 @@ public static String format(HTTPSampleResult sampleResult) { && contentType.toLowerCase(Locale.ROOT).startsWith(HTTPConstants.MULTIPART_FORM_DATA); // Multipart bodies are rebuilt as -F flags; curl then sets its own // Content-Type (with its own boundary), so the original one is dropped. - List formParts = hasBody && isMultipart ? parseMultipartForm(contentType, body) : List.of(); + List formParts = hasBody && isMultipart ? parseMultipartForm(contentType, body) : List.of(); boolean emitsForm = !formParts.isEmpty(); boolean emitsDataRaw = hasBody && !isMultipart && !containsPlaceholder(body); @@ -155,6 +155,10 @@ public static String format(HTTPSampleResult sampleResult) { if (emitsForm && HTTPConstants.HEADER_CONTENT_TYPE.equalsIgnoreCase(header[0])) { continue; } + // --compressed (below) makes curl send its own Accept-Encoding, so the explicit one is redundant. + if (acceptsEncoding && ACCEPT_ENCODING.equalsIgnoreCase(header[0])) { + continue; + } sb.append(NEWLINE).append("-H ").append(quote(header[0] + ": " + header[1])); //$NON-NLS-1$ //$NON-NLS-2$ } @@ -170,8 +174,8 @@ public static String format(HTTPSampleResult sampleResult) { } if (emitsForm) { - for (String part : formParts) { - sb.append(NEWLINE).append("-F ").append(quote(part)); //$NON-NLS-1$ + for (String[] part : formParts) { + sb.append(NEWLINE).append(part[0]).append(' ').append(quote(part[1])); } } else if (emitsDataRaw) { sb.append(NEWLINE).append("--data-raw ").append(quote(body)); //$NON-NLS-1$ @@ -194,7 +198,7 @@ public static String format(HTTPSampleResult sampleResult) { * * @return the form parts, or an empty list if the body cannot be parsed */ - private static List parseMultipartForm(String contentType, String body) { + private static List parseMultipartForm(String contentType, String body) { String boundary = extractBoundary(contentType); if (StringUtilities.isBlank(boundary)) { return List.of(); @@ -205,18 +209,20 @@ private static List parseMultipartForm(String contentType, String body) } catch (RuntimeException e) { // NOSONAR malformed body: fall back to the omitted-body note return List.of(); } - List parts = new ArrayList<>(); + List parts = new ArrayList<>(); for (JMeterProperty property : multipart.getArguments()) { Argument argument = (Argument) property.getObjectValue(); - parts.add(argument.getName() + "=" + argument.getValue()); //$NON-NLS-1$ + // --form-string takes the value verbatim; -F would treat a leading + // '@' or '<' in the value as a file reference and misinterpret the field. + parts.add(new String[] { "--form-string", argument.getName() + "=" + argument.getValue() }); //$NON-NLS-1$ //$NON-NLS-2$ } for (HTTPFileArg file : multipart.getHTTPFileArgs().asArray()) { - StringBuilder part = new StringBuilder(); - part.append(file.getParamName()).append("=@").append(file.getPath()); //$NON-NLS-1$ + StringBuilder spec = new StringBuilder(); + spec.append(file.getParamName()).append("=@").append(file.getPath()); //$NON-NLS-1$ if (StringUtilities.isNotEmpty(file.getMimeType())) { - part.append(";type=").append(file.getMimeType()); //$NON-NLS-1$ + spec.append(";type=").append(file.getMimeType()); //$NON-NLS-1$ } - parts.add(part.toString()); + parts.add(new String[] { "-F", spec.toString() }); //$NON-NLS-1$ } return parts; } diff --git a/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatterTest.java b/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatterTest.java index 406013b259d..d76899cc6b1 100644 --- a/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatterTest.java +++ b/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatterTest.java @@ -137,13 +137,30 @@ void testMultipartRebuiltAsFormFlagsWithFileName() throws Exception { String curl = CurlCommandFormatter.format(res); // The file part is rebuilt with the file name as an editable @placeholder. assertTrue(curl.contains("-F 'upload=@report.pdf;type=application/pdf'"), curl); - assertTrue(curl.contains("-F 'comment=hello'"), curl); + // Regular fields use --form-string so the value is never treated as a file. + assertTrue(curl.contains("--form-string 'comment=hello'"), curl); // No raw dump of the placeholder, and curl sets its own multipart Content-Type. assertFalse(curl.contains("--data-raw"), curl); assertFalse(curl.contains("actual file content"), curl); assertFalse(curl.contains("-H 'Content-Type: multipart/form-data"), curl); } + @Test + void testMultipartTextFieldWithAtPrefixUsesFormString() throws Exception { + HTTPSampleResult res = result("POST", "http://example.com/upload"); + res.setRequestHeaders("Content-Type: multipart/form-data; boundary=xyz"); + // A legitimate text field whose value starts with '@' must not be read as a file. + res.setQueryString("--xyz\r\n" + + "Content-Disposition: form-data; name=\"handle\"\r\n" + + "\r\n" + + "@someuser\r\n" + + "--xyz--\r\n"); + + String curl = CurlCommandFormatter.format(res); + assertTrue(curl.contains("--form-string 'handle=@someuser'"), curl); + assertFalse(curl.contains("-F 'handle=@someuser'"), curl); + } + @Test void testFileAsBodyPlaceholderIsNotReproduced() throws Exception { HTTPSampleResult res = result("POST", "http://example.com/upload"); @@ -186,7 +203,8 @@ void testAcceptEncodingAddsCompressed() throws Exception { String curl = CurlCommandFormatter.format(res); assertTrue(curl.contains("--compressed"), curl); - assertTrue(curl.contains("-H 'Accept-Encoding: gzip, deflate'"), curl); + // --compressed makes curl send its own Accept-Encoding, so the explicit one is dropped. + assertFalse(curl.contains("-H 'Accept-Encoding"), curl); } @Test diff --git a/xdocs/usermanual/component_reference.xml b/xdocs/usermanual/component_reference.xml index abcdf241699..2d1a59380ba 100644 --- a/xdocs/usermanual/component_reference.xml +++ b/xdocs/usermanual/component_reference.xml @@ -2803,7 +2803,7 @@ For HTTP samples the Request panel also provides a cURL tab that re ready-to-run curl command, so it can be copied to a console or shared with a developer. The command targets a POSIX-compatible shell (it is not valid cmd.exe or PowerShell syntax). It reproduces whatever the sample carried, including Authorization headers, cookies and API keys, -so treat it as sensitive when sharing. Multipart uploads are rendered as -F form parts using the +so treat it as sensitive when sharing. Multipart uploads are rendered as curl form parts using the original field and file names; since JMeter does not keep the uploaded bytes, a file is referenced as @filename, a placeholder to edit to a real path before running the command. A file sent as the whole request body, or a non-repeatable body, cannot be shown at all and is omitted with a note.

    From e959fab302fc4a0a2ef155b4d587c9a49af67052 Mon Sep 17 00:00:00 2001 From: poliakov-alex Date: Sat, 8 Aug 2026 01:57:26 -0400 Subject: [PATCH 4/5] PR #6736 edits based on comments from code review. Part 3 --- .../http/curl/CurlCommandFormatter.java | 5 +++-- .../protocol/http/sampler/HTTPHC4Impl.java | 6 +++--- .../protocol/http/sampler/PostWriter.java | 17 +++++++++++++++-- 3 files changed, 21 insertions(+), 7 deletions(-) diff --git a/src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatter.java b/src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatter.java index 19d02237b4c..7d872e1828f 100644 --- a/src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatter.java +++ b/src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatter.java @@ -26,6 +26,7 @@ import org.apache.jmeter.config.Argument; import org.apache.jmeter.protocol.http.config.MultipartUrlConfig; import org.apache.jmeter.protocol.http.sampler.HTTPSampleResult; +import org.apache.jmeter.protocol.http.sampler.PostWriter; import org.apache.jmeter.protocol.http.util.HTTPConstants; import org.apache.jmeter.protocol.http.util.HTTPFileArg; import org.apache.jmeter.testelement.property.JMeterProperty; @@ -76,8 +77,8 @@ public final class CurlCommandFormatter { * @see org.apache.jmeter.protocol.http.sampler.PostWriter */ private static final String[] BODY_PLACEHOLDERS = { - "", //$NON-NLS-1$ - "" //$NON-NLS-1$ + PostWriter.FILE_CONTENT_PLACEHOLDER, + PostWriter.NON_REPEATABLE_ENTITY_PLACEHOLDER }; private CurlCommandFormatter() { diff --git a/src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/sampler/HTTPHC4Impl.java b/src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/sampler/HTTPHC4Impl.java index 569bb164b6a..7b36dc3be49 100644 --- a/src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/sampler/HTTPHC4Impl.java +++ b/src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/sampler/HTTPHC4Impl.java @@ -1494,7 +1494,7 @@ private static String getFromHeadersMatchingPredicate(HttpRequest method, Predic // Helper class so we can generate request data without dumping entire file contents private static class ViewableFileBody extends FileBody { private static final byte[] CONTENTS_OMITTED = - "".getBytes(StandardCharsets.UTF_8); + PostWriter.FILE_CONTENT_PLACEHOLDER.getBytes(StandardCharsets.UTF_8); private boolean hideFileData; private ViewableFileBody(File file, ContentType contentType, Charset charset) { @@ -1619,7 +1619,7 @@ else if(ADD_CONTENT_TYPE_TO_POST_IF_MISSING) { entityEnclosingRequest.setEntity(fileRequestEntity); // We just add placeholder text for file content - postedBody.append(""); + postedBody.append(PostWriter.FILE_CONTENT_PLACEHOLDER); } else { // In a post request which is not multipart, we only support // parameters, no file upload is allowed @@ -1693,7 +1693,7 @@ private static void writeEntityToSB(final StringBuilder postedBody, final HttpEn : contentEncoding)); bos.close(); } else { - postedBody.append(""); // $NON-NLS-1$ + postedBody.append(PostWriter.NON_REPEATABLE_ENTITY_PLACEHOLDER); } } diff --git a/src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/sampler/PostWriter.java b/src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/sampler/PostWriter.java index 21a413ec768..307428078a8 100644 --- a/src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/sampler/PostWriter.java +++ b/src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/sampler/PostWriter.java @@ -56,6 +56,19 @@ public class PostWriter { public static final String ENCODING = StandardCharsets.UTF_8.name(); + /** + * Placeholder written into the rendered request body in place of the actual + * file content, which JMeter does not keep (shown in the View Results Tree). + */ + public static final String FILE_CONTENT_PLACEHOLDER = ""; // $NON-NLS-1$ + + /** + * Placeholder written into the rendered request body when the entity is not + * repeatable and the bytes that were sent cannot be shown. + */ + public static final String NON_REPEATABLE_ENTITY_PLACEHOLDER = + ""; // $NON-NLS-1$ + /** The form data that is going to be sent as url encoded */ protected byte[] formDataUrlEncoded; /** The form data that is going to be sent in post body */ @@ -134,7 +147,7 @@ public String sendPostData(URLConnection connection, HTTPSamplerBase sampler) th // Write the actual file content writeFileToStream(file.getPath(), out); // We just add placeholder text for file content - postedBody.append(""); // $NON-NLS-1$ + postedBody.append(FILE_CONTENT_PLACEHOLDER); out.write(CRLF); postedBody.append(CRLF_STRING); } @@ -158,7 +171,7 @@ public String sendPostData(URLConnection connection, HTTPSamplerBase sampler) th out.close(); // We just add placeholder text for file content - postedBody.append(""); // $NON-NLS-1$ + postedBody.append(FILE_CONTENT_PLACEHOLDER); } else if (formDataUrlEncoded != null){ // may be null for PUT // In an application/x-www-form-urlencoded request, we only support From 9b8b47bef4be04d93a10d2ddace5d8f6e8a88a91 Mon Sep 17 00:00:00 2001 From: poliakov-alex Date: Fri, 14 Aug 2026 16:48:01 -0400 Subject: [PATCH 5/5] PR #6736 edits based on comments from code review. Part 4 - Multipart text fields now use --form-string with a per-part -F ...;type= only for a non-default content type, so a value starting with @/< or containing ; is never misread by curl. - File names are double-quoted inside the -F spec so ';'/',' in a name are not parsed as curl option separators. - extractBoundary strips a quoted boundary and the parser only runs when the body actually contains the delimiter; a mismatched boundary falls back to the omitted-body note. RequestViewHTTP now reuses this shared method. - Keep the explicit Accept-Encoding header alongside --compressed (curl would otherwise negotiate its own build-dependent list). - Skip -b when a Cookie header was already emitted (AjpSampler can carry both). - Reword the omitted-body note as reason-then-consequence. - Extend the round-trip tests through BasicCurlParser to --head, --compressed and multipart, plus quoted/mismatched boundary and special-char file names. --- .../jmeter/resources/messages.properties | 2 +- .../http/curl/CurlCommandFormatter.java | 90 +++++++++---- .../http/visualizers/RequestViewHTTP.java | 19 +-- .../http/curl/CurlCommandFormatterTest.java | 118 +++++++++++++++++- 4 files changed, 185 insertions(+), 44 deletions(-) diff --git a/src/core/src/main/resources/org/apache/jmeter/resources/messages.properties b/src/core/src/main/resources/org/apache/jmeter/resources/messages.properties index dd04c9bc8b4..2fc729bf526 100644 --- a/src/core/src/main/resources/org/apache/jmeter/resources/messages.properties +++ b/src/core/src/main/resources/org/apache/jmeter/resources/messages.properties @@ -1457,7 +1457,7 @@ view_results_table_request_params_key=Parameter name view_results_table_request_params_value=Value view_results_table_request_raw_nodata=No data to display view_results_table_request_tab_curl=cURL -view_results_table_request_tab_curl_body_omitted=Request body not shown (file sent as body or non-repeatable content) and cannot be reproduced +view_results_table_request_tab_curl_body_omitted=Request body cannot be reproduced: JMeter does not keep the bytes of a file sent as the body or of a non-repeatable entity view_results_table_request_tab_http=HTTP view_results_table_request_tab_raw=Raw view_results_table_result_tab_parsed=Parsed diff --git a/src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatter.java b/src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatter.java index 7d872e1828f..9efa3b6448e 100644 --- a/src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatter.java +++ b/src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatter.java @@ -23,10 +23,10 @@ import java.util.Locale; import java.util.Set; -import org.apache.jmeter.config.Argument; import org.apache.jmeter.protocol.http.config.MultipartUrlConfig; import org.apache.jmeter.protocol.http.sampler.HTTPSampleResult; import org.apache.jmeter.protocol.http.sampler.PostWriter; +import org.apache.jmeter.protocol.http.util.HTTPArgument; import org.apache.jmeter.protocol.http.util.HTTPConstants; import org.apache.jmeter.protocol.http.util.HTTPFileArg; import org.apache.jmeter.testelement.property.JMeterProperty; @@ -53,6 +53,9 @@ public final class CurlCommandFormatter { private static final String BOUNDARY = "boundary="; //$NON-NLS-1$ + /** {@code HTTPArgument} defaults a part's content type to this; see HTTPArgumentSchema. */ + private static final String DEFAULT_FIELD_CONTENT_TYPE = "text/plain"; //$NON-NLS-1$ + /** * Headers that must not be reproduced in the curl command: curl generates * them itself, they are connection-specific (hop-by-hop) headers that are @@ -152,25 +155,30 @@ public static String format(HTTPSampleResult sampleResult) { sb.append(NEWLINE).append(quote(url.toString())); } + boolean hasCookieHeader = false; for (String[] header : headers) { if (emitsForm && HTTPConstants.HEADER_CONTENT_TYPE.equalsIgnoreCase(header[0])) { continue; } - // --compressed (below) makes curl send its own Accept-Encoding, so the explicit one is redundant. - if (acceptsEncoding && ACCEPT_ENCODING.equalsIgnoreCase(header[0])) { - continue; + if (HTTPConstants.HEADER_COOKIE.equalsIgnoreCase(header[0])) { + hasCookieHeader = true; } sb.append(NEWLINE).append("-H ").append(quote(header[0] + ": " + header[1])); //$NON-NLS-1$ //$NON-NLS-2$ } - // HttpClient disables automatic decompression, so Accept-Encoding is only - // present when explicitly set; --compressed makes curl decode the response. + // HttpClient disables automatic decompression, so Accept-Encoding is only present + // when explicitly set. --compressed makes curl decode the response; it is kept + // alongside the explicit header rather than replacing it, because curl otherwise + // negotiates its own build-dependent encoding list the test plan never asked for. if (acceptsEncoding) { sb.append(NEWLINE).append("--compressed"); //$NON-NLS-1$ } + // Cookies normally arrive through getCookies(), but AjpSampler can also leave a + // Cookie header in the list; curl lets the header win and silently drops -b, so + // only add -b when no Cookie header was emitted. String cookies = sampleResult.getCookies(); - if (StringUtilities.isNotEmpty(cookies)) { + if (!hasCookieHeader && StringUtilities.isNotEmpty(cookies)) { sb.append(NEWLINE).append("-b ").append(quote(cookies)); //$NON-NLS-1$ } @@ -201,7 +209,10 @@ public static String format(HTTPSampleResult sampleResult) { */ private static List parseMultipartForm(String contentType, String body) { String boundary = extractBoundary(contentType); - if (StringUtilities.isBlank(boundary)) { + // A quoted boundary is unquoted above; but if the header boundary and the body + // disagree, MultipartUrlConfig would treat the whole body as one field and emit + // garbage, so require the delimiter to be present and fall back to the note otherwise. + if (StringUtilities.isBlank(boundary) || !body.contains("--" + boundary)) { //$NON-NLS-1$ return List.of(); } MultipartUrlConfig multipart = new MultipartUrlConfig(boundary); @@ -212,27 +223,56 @@ private static List parseMultipartForm(String contentType, String body } List parts = new ArrayList<>(); for (JMeterProperty property : multipart.getArguments()) { - Argument argument = (Argument) property.getObjectValue(); - // --form-string takes the value verbatim; -F would treat a leading - // '@' or '<' in the value as a file reference and misinterpret the field. - parts.add(new String[] { "--form-string", argument.getName() + "=" + argument.getValue() }); //$NON-NLS-1$ //$NON-NLS-2$ + parts.add(formField((HTTPArgument) property.getObjectValue())); } for (HTTPFileArg file : multipart.getHTTPFileArgs().asArray()) { - StringBuilder spec = new StringBuilder(); - spec.append(file.getParamName()).append("=@").append(file.getPath()); //$NON-NLS-1$ - if (StringUtilities.isNotEmpty(file.getMimeType())) { - spec.append(";type=").append(file.getMimeType()); //$NON-NLS-1$ - } - parts.add(new String[] { "-F", spec.toString() }); //$NON-NLS-1$ + parts.add(fileField(file)); } return parts; } /** - * @return the {@code boundary} value of a multipart content type, or - * {@code null} if it is absent + * A multipart text field. {@code --form-string} keeps the value verbatim (curl would + * otherwise read a leading {@code @} or {@code <} as a file reference), but it cannot + * carry a per-part content type; {@code -F} can, so it is used when the value is safe + * for it (no {@code @}/{@code <} prefix and no {@code ;} that curl would read as an + * option separator). + */ + private static String[] formField(HTTPArgument argument) { + String value = argument.getValue() == null ? "" : argument.getValue(); //$NON-NLS-1$ + String type = argument.getContentType(); + // HTTPArgument defaults content_type to text/plain, which is indistinguishable from + // a part that carried none; only a non-default type is worth reproducing. + boolean hasType = StringUtilities.isNotEmpty(type) && !DEFAULT_FIELD_CONTENT_TYPE.equalsIgnoreCase(type); + boolean safeForF = hasType + && !value.startsWith("@") && !value.startsWith("<") && value.indexOf(';') < 0; //$NON-NLS-1$ //$NON-NLS-2$ + if (safeForF) { + return new String[] { "-F", argument.getName() + "=" + value + ";type=" + type }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + return new String[] { "--form-string", argument.getName() + "=" + value }; //$NON-NLS-1$ //$NON-NLS-2$ + } + + /** + * A multipart file part. The file name is double-quoted inside the spec so that a name + * containing {@code ;} or {@code ,} is not parsed by curl as an option separator; the + * bytes are not kept by JMeter, so the name is a placeholder to edit to a real path. */ - private static String extractBoundary(String contentType) { + private static String[] fileField(HTTPFileArg file) { + StringBuilder spec = new StringBuilder(); + spec.append(file.getParamName()).append("=@\"").append(file.getPath()).append('"'); //$NON-NLS-1$ + if (StringUtilities.isNotEmpty(file.getMimeType())) { + spec.append(";type=").append(file.getMimeType()); //$NON-NLS-1$ + } + return new String[] { "-F", spec.toString() }; //$NON-NLS-1$ + } + + /** + * Extract the {@code boundary} value of a multipart content type, unquoted. + * + * @param contentType a {@code Content-Type} header value + * @return the boundary, or {@code null} if it is absent + */ + public static String extractBoundary(String contentType) { int index = contentType.toLowerCase(Locale.ROOT).indexOf(BOUNDARY); if (index < 0) { return null; @@ -242,7 +282,13 @@ private static String extractBoundary(String contentType) { if (semicolon >= 0) { boundary = boundary.substring(0, semicolon); } - return boundary.trim(); + boundary = boundary.trim(); + // RFC 2046 allows the boundary to be quoted; MultipartUrlConfig expects it unquoted. + if (boundary.length() >= 2 && boundary.charAt(0) == '"' + && boundary.charAt(boundary.length() - 1) == '"') { + boundary = boundary.substring(1, boundary.length() - 1); + } + return boundary; } private static boolean containsPlaceholder(String body) { diff --git a/src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/visualizers/RequestViewHTTP.java b/src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/visualizers/RequestViewHTTP.java index 57fac44892f..41ef5110d53 100644 --- a/src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/visualizers/RequestViewHTTP.java +++ b/src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/visualizers/RequestViewHTTP.java @@ -40,6 +40,7 @@ import org.apache.jmeter.gui.util.HeaderAsPropertyRenderer; import org.apache.jmeter.gui.util.TextBoxDialoger.TextBoxDoubleClick; import org.apache.jmeter.protocol.http.config.MultipartUrlConfig; +import org.apache.jmeter.protocol.http.curl.CurlCommandFormatter; import org.apache.jmeter.protocol.http.sampler.HTTPSampleResult; import org.apache.jmeter.protocol.http.util.HTTPConstants; import org.apache.jmeter.testelement.property.JMeterProperty; @@ -216,7 +217,7 @@ public void setSamplerResult(Object objectResult) { if (isMultipart && StringUtilities.isNotBlank(queryPost)) { String contentType = lhm.get(HTTPConstants.HEADER_CONTENT_TYPE); - String boundaryString = extractBoundary(contentType); + String boundaryString = CurlCommandFormatter.extractBoundary(contentType); MultipartUrlConfig urlconfig = new MultipartUrlConfig(boundaryString); urlconfig.parseArguments(queryPost); @@ -243,22 +244,6 @@ public void setSamplerResult(Object objectResult) { } } - /** - * Extract the multipart boundary - * @param contentType the content type header - * @return the boundary string - */ - private static String extractBoundary(String contentType) { - // Get the boundary string for the multiparts from the content type - String boundaryString = contentType.substring(contentType.toLowerCase(java.util.Locale.ENGLISH).indexOf("boundary=") + "boundary=".length()); - //TODO check in the RFC if other char can be used as separator - String[] split = boundaryString.split(";"); - if(split.length > 1) { - boundaryString = split[0]; - } - return boundaryString; - } - /** * check if the request is multipart * @param headers the http request headers diff --git a/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatterTest.java b/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatterTest.java index d76899cc6b1..b5b370646ba 100644 --- a/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatterTest.java +++ b/src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatterTest.java @@ -135,8 +135,8 @@ void testMultipartRebuiltAsFormFlagsWithFileName() throws Exception { + "--xyz--\r\n"); String curl = CurlCommandFormatter.format(res); - // The file part is rebuilt with the file name as an editable @placeholder. - assertTrue(curl.contains("-F 'upload=@report.pdf;type=application/pdf'"), curl); + // The file part is rebuilt with the file name as an editable, double-quoted @placeholder. + assertTrue(curl.contains("-F 'upload=@\"report.pdf\";type=application/pdf'"), curl); // Regular fields use --form-string so the value is never treated as a file. assertTrue(curl.contains("--form-string 'comment=hello'"), curl); // No raw dump of the placeholder, and curl sets its own multipart Content-Type. @@ -203,8 +203,9 @@ void testAcceptEncodingAddsCompressed() throws Exception { String curl = CurlCommandFormatter.format(res); assertTrue(curl.contains("--compressed"), curl); - // --compressed makes curl send its own Accept-Encoding, so the explicit one is dropped. - assertFalse(curl.contains("-H 'Accept-Encoding"), curl); + // The explicit header is kept alongside --compressed so the request is unchanged + // (curl would otherwise negotiate its own build-dependent encoding list). + assertTrue(curl.contains("-H 'Accept-Encoding: gzip, deflate'"), curl); } @Test @@ -254,4 +255,113 @@ void testRoundTripPreservesDuplicateHeaders() throws Exception { .collect(Collectors.toList()); assertEquals(List.of("text/html", "application/json"), accept); } + + private static HTTPSampleResult multipart(String boundaryHeader, String body) throws MalformedURLException { + HTTPSampleResult res = result("POST", "http://example.com/upload"); + res.setRequestHeaders("Content-Type: multipart/form-data; boundary=" + boundaryHeader); + res.setQueryString(body); + return res; + } + + @Test + void testQuotedBoundaryIsUnquotedAndParsed() throws Exception { + // RFC 2046 allows a quoted boundary; it must still parse, not swallow the trailer. + HTTPSampleResult res = multipart("\"xyz\"", + "--xyz\r\nContent-Disposition: form-data; name=\"a\"\r\n\r\nb\r\n--xyz--\r\n"); + + String curl = CurlCommandFormatter.format(res); + assertTrue(curl.contains("--form-string 'a=b'"), curl); + assertFalse(curl.contains("--xyz--"), curl); + } + + @Test + void testBoundaryDisagreeingWithBodyFallsBackToNote() throws Exception { + HTTPSampleResult res = multipart("nomatch", + "--other\r\nContent-Disposition: form-data; name=\"a\"\r\n\r\nb\r\n--other--\r\n"); + + String curl = CurlCommandFormatter.format(res); + assertFalse(curl.contains("--form-string"), curl); + assertFalse(curl.contains("-F "), curl); + assertTrue(curl.contains("\n# "), curl); + } + + @Test + void testFileNameWithSemicolonOrCommaIsDoubleQuoted() throws Exception { + HTTPSampleResult res = multipart("xyz", + "--xyz\r\nContent-Disposition: form-data; name=\"up\"; filename=\"a;b,c.txt\"\r\n" + + "Content-Type: text/plain\r\n\r\n\r\n--xyz--\r\n"); + + assertTrue(CurlCommandFormatter.format(res).contains("-F 'up=@\"a;b,c.txt\";type=text/plain'"), + CurlCommandFormatter.format(res)); + } + + @Test + void testMultipartFieldContentTypeIsPreservedViaF() throws Exception { + HTTPSampleResult res = multipart("xyz", + "--xyz\r\nContent-Disposition: form-data; name=\"meta\"\r\n" + + "Content-Type: application/json\r\n\r\n{\"a\":1}\r\n--xyz--\r\n"); + + assertTrue(CurlCommandFormatter.format(res).contains("-F 'meta={\"a\":1};type=application/json'"), + CurlCommandFormatter.format(res)); + } + + @Test + void testMultipartFieldWithTypeButUnsafeValueFallsBackToFormString() throws Exception { + // A content type is set, but the value would be read as a file by -F, so the + // verbatim --form-string wins and the (now unrepresentable) type is dropped. + HTTPSampleResult res = multipart("xyz", + "--xyz\r\nContent-Disposition: form-data; name=\"meta\"\r\n" + + "Content-Type: application/json\r\n\r\n@ref\r\n--xyz--\r\n"); + + String curl = CurlCommandFormatter.format(res); + assertTrue(curl.contains("--form-string 'meta=@ref'"), curl); + assertFalse(curl.contains("-F 'meta="), curl); + } + + @Test + void testCookieHeaderSuppressesDashB() throws Exception { + // AjpSampler can leave a Cookie header while getCookies() is also filled; curl lets + // the header win, so -b must not be emitted or its cookies would be silently dropped. + HTTPSampleResult res = result("GET", "http://example.com/"); + res.setRequestHeaders("Cookie: a=1"); + res.setCookies("b=2"); + + String curl = CurlCommandFormatter.format(res); + assertTrue(curl.contains("-H 'Cookie: a=1'"), curl); + assertFalse(curl.contains("-b "), curl); + } + + @Test + void testRoundTripHead() throws Exception { + HTTPSampleResult res = result("HEAD", "http://example.com/"); + + BasicCurlParser.Request parsed = new BasicCurlParser().parse(CurlCommandFormatter.format(res)); + assertEquals("HEAD", parsed.getMethod()); + assertEquals("http://example.com/", parsed.getUrl()); + } + + @Test + void testRoundTripCompressed() throws Exception { + HTTPSampleResult res = result("GET", "http://example.com/"); + res.setRequestHeaders("Accept-Encoding: gzip, deflate"); + + BasicCurlParser.Request parsed = new BasicCurlParser().parse(CurlCommandFormatter.format(res)); + assertTrue(parsed.isCompressed()); + assertTrue(parsed.getHeaders().stream().anyMatch(e -> "Accept-Encoding".equals(e.getKey()))); + } + + @Test + void testRoundTripMultipartFieldAndFile() throws Exception { + HTTPSampleResult res = multipart("xyz", + "--xyz\r\nContent-Disposition: form-data; name=\"comment\"\r\n\r\nhello\r\n" + + "--xyz\r\nContent-Disposition: form-data; name=\"upload\"; filename=\"report.pdf\"\r\n" + + "Content-Type: application/pdf\r\n\r\n\r\n--xyz--\r\n"); + + BasicCurlParser.Request parsed = new BasicCurlParser().parse(CurlCommandFormatter.format(res)); + assertEquals("POST", parsed.getMethod()); + assertTrue(parsed.getFormStringData().stream() + .anyMatch(e -> "comment".equals(e.getKey()) && "hello".equals(e.getValue())), + parsed.getFormStringData().toString()); + assertFalse(parsed.getFormData().isEmpty()); + } }