You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@jmeter.apache.org by "poliakov-alex (via GitHub)" <gi...@apache.org> on 2026/07/24 23:50:36 UTC

[PR] feat(http): add cURL tab to View Results Tree Request panel [jmeter]

poliakov-alex opened a new pull request, #6736:
URL: https://github.com/apache/jmeter/pull/6736

   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 or shared.
   
   Closes #6375
   
   ## Description
   Adds a cURL tab to the Request panel of the View Results Tree listener, next to the existing Raw and HTTP tabs. It renders the sampled HTTP request as a ready-to-run curl command that can be copied or shared.
   
   The command includes the method (-X), the URL, request headers (-H), cookies (-b), and the request body (--data-raw). Values are single-quoted and shell-escaped so the output is paste-safe.
   
   Connection-specific (hop-by-hop) and curl-managed headers — Connection, Keep-Alive, Proxy-Connection, Transfer-Encoding, Upgrade, Content-Length — are omitted, because reproducing them makes the request fail (e.g. Connection is forbidden in HTTP/2 and produces curl: (92) ... PROTOCOL_ERROR, and a manual Content-Length conflicts with the body curl computes).
   
   The tab is contributed through the existing RequestView service interface (@AutoService), so no wiring changes were needed in RequestPanel.
   
   ## Motivation and Context
   Fixes [#6375](https://github.com/apache/jmeter/issues/6375). Users frequently need to reproduce a sampled request outside JMeter — in a terminal or when handing it to a developer. Today they must reconstruct the curl command by hand from the Raw/HTTP tabs.
   
   ## How Has This Been Tested?
   Added RequestViewCurlTest (8 JUnit tests) covering GET, headers, POST body, header skipping, cookie handling / de-duplication, single-quote escaping, and a null URL.
   Ran ./gradlew :src:protocol:http:test, checkstyleMain, checkstyleTest, autostyleJavaCheck — all green.
   Manually verified in the GUI: ran an HTTP sampler, opened View Results Tree → Request → cURL, copied the command and executed it in a terminal successfully.
   
   ## Screenshots (if appropriate):
   <img width="1382" height="867" alt="image" src="https://github.com/user-attachments/assets/a350792f-b710-4771-a768-48ddf6220486" />
   
   ## Types of changes
   New feature (non-breaking change which adds functionality)
   
   ## Checklist:
   - [ ] My code follows the [code style][style-guide] of this project.
   - [ ] I have updated the documentation accordingly.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@jmeter.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(http): add cURL tab to View Results Tree Request panel [jmeter]

Posted by "poliakov-alex (via GitHub)" <gi...@apache.org>.
poliakov-alex commented on code in PR #6736:
URL: https://github.com/apache/jmeter/pull/6736#discussion_r3797057677


##########
src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatter.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.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;
+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.
+ *
+ * <p>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.</p>
+ *
+ * <p>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).</p>
+ */
+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$
+
+    /** {@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
+     * 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<String> 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 = {
+            PostWriter.FILE_CONTENT_PLACEHOLDER,
+            PostWriter.NON_REPEATABLE_ENTITY_PLACEHOLDER
+    };
+
+    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<String[]> 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.equalsIgnoreCase(name)) {
+                    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<String[]> 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()));
+        }
+
+        boolean hasCookieHeader = false;
+        for (String[] header : headers) {
+            if (emitsForm && HTTPConstants.HEADER_CONTENT_TYPE.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; 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 (!hasCookieHeader && StringUtilities.isNotEmpty(cookies)) {
+            sb.append(NEWLINE).append("-b ").append(quote(cookies)); //$NON-NLS-1$
+        }
+
+        if (emitsForm) {
+            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$
+        } 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<String[]> parseMultipartForm(String contentType, String body) {
+        String boundary = extractBoundary(contentType);
+        // 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);
+        try {
+            multipart.parseArguments(body);
+        } catch (RuntimeException e) { // NOSONAR malformed body: fall back to the omitted-body note
+            return List.of();
+        }

Review Comment:
   Now emits -F 'name=value;type=…' for a non-default type when the value is -F-safe (no leading @/<, no ;), else --form-string. Gotcha: HTTPArgument defaults content_type to text/plain (HTTPArgumentSchema), indistinguishable from none, so I treat text/plain as unset — application/json is preserved, plain fields stay --form-string. Tests: testMultipartFieldContentTypeIsPreservedViaF, testMultipartFieldWithTypeButUnsafeValueFallsBackToFormString.
   On the two smaller notes: the no-separator case is guarded (renders name=, not name=null). Field/file interleaving is still lost, since MultipartUrlConfig returns fields and files as separate collections — preserving order would mean parsing the body here instead of reusing it. Left as-is (part order rarely matters)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@jmeter.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(http): add cURL tab to View Results Tree Request panel [jmeter]

Posted by "vlsi (via GitHub)" <gi...@apache.org>.
vlsi commented on code in PR #6736:
URL: https://github.com/apache/jmeter/pull/6736#discussion_r3650891751


##########
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<String> SKIPPED_HEADERS = Set.of(

Review Comment:
   **`X-LocalAddress` should be skipped: it never went on the wire.**
   
   When a sampler has a source address configured, JMeter injects a pseudo-header into the result purely for display:
   
   - `HTTPHC4Impl#657` — `request.addHeader(HEADER_LOCAL_ADDRESS, localAddress.toString())`, immediately before `res.setRequestHeaders(...)`
   - `HTTPConstantsInterface#75` — `String HEADER_LOCAL_ADDRESS = "X-LocalAddress"; // pseudo-header for reporting Local Address`
   
   The curl tab copies it verbatim, so those samples render `-H 'X-LocalAddress: /10.0.0.5'`. Adding `"x-localaddress"` to `SKIPPED_HEADERS` covers it.



##########
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<String> 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<String, String> headers = JMeterUtils.parseHeaders(requestHeaders);

Review Comment:
   **Repeated headers are silently collapsed, so the command does not reproduce the request.**
   
   `JMeterUtils.parseHeaders` returns a `LinkedHashMap<String, String>`, so only the last value survives per header name. Repeated headers do reach `requestHeaders`: `HeaderManager` entries go through `request.addHeader` (`HTTPHC4Impl#1415`), and `getFromHeadersMatchingPredicate` (`HTTPHC4Impl#1477`) writes every `Header` instance on its own line.
   
   Verified against this branch:
   
   ```
   input:  X-Trace: a\nX-Trace: b\nAccept: text/html\nAccept: application/json
   
   output: curl -X 'GET' \
             'http://example.com/' \
             -H 'X-Trace: b' \
             -H 'Accept: application/json'
   ```
   
   `X-Trace: a` and `Accept: text/html` are gone. For the HTTP tab that is a display quirk; for a command advertised as ready to run it is a different request. Splitting `requestHeaders` line by line here, instead of delegating to `parseHeaders`, keeps the duplicates.



##########
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<String> 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)) {

Review Comment:
   **`HEAD` samples render a command that fails.**
   
   `-X` is emitted for every method, so a HEAD sample becomes `curl -X 'HEAD' '<url>'`. curl sends HEAD but still waits for a response body. Against a local server:
   
   ```console
   $ curl -X 'HEAD' 'http://127.0.0.1:18099/' -o /dev/null
   curl: (18) transfer closed with 340 bytes remaining to read   # exit 18
   
   $ curl -I 'http://127.0.0.1:18099/' -o /dev/null              # exit 0
   ```
   
   On a keep-alive connection it hangs until the transfer times out instead of failing fast. `HEAD` needs `--head` rather than `-X 'HEAD'`. This overlaps the `-X` note on line 108 — both fall out of one branch on the method.



##########
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<String> 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<String, String> headers = JMeterUtils.parseHeaders(requestHeaders);
+            for (Map.Entry<String, String> 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$

Review Comment:
   **Consider adding `--compressed` when `Accept-Encoding` is reproduced.**
   
   HttpClient4 disables automatic content compression (`HTTPHC4Impl#1150`), so `Accept-Encoding` shows up only when a Header Manager sets it — which is common, and the recorder template does it. The header is then copied into the command without `--compressed`, and curl prints the gzip stream to the terminal.



##########
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$

Review Comment:
   **The output is POSIX-shell syntax, with nothing saying so.**
   
   `NEWLINE` is a backslash line continuation, and `quote()` on line 154 uses single quotes with the `'\''` idiom. Neither works in `cmd.exe`, which has no single-quote quoting at all, or in PowerShell, which doubles `''` and continues lines with a backtick. A large share of View Results Tree users are on Windows.
   
   Two options that both beat the status quo: emit the command on one line, so only the quoting differs; or state in `component_reference.xml` that the command targets a POSIX-compatible shell.



##########
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<String> 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<String, String> headers = JMeterUtils.parseHeaders(requestHeaders);
+            for (Map.Entry<String, String> 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$

Review Comment:
   **Two more paths put a placeholder into `--data-raw`, and neither is multipart.**
   
   Extending the multipart note on line 141: filtering on `multipart/form-data` alone leaves two cases that produce the same silently wrong command.
   
   - File sent as the request body, where `Content-Type` is the file's own type rather than multipart. `HTTPHC4Impl#1545` appends `<actual file content, not shown here>` in the `getSendFileAsPostBody` branch.
   - Non-repeatable entity. `HTTPHC4Impl#1619` appends `<Entity was not repeatable, cannot view what was sent>`.
   
   Both render as `--data-raw '<actual file content, not shown here>'` and the equivalent. Detecting "this body is a rendered placeholder, not the wire body" covers all three cases; a multipart check covers one.
   
   Separately, line 140 uses `isNotBlank`, which drops a body made only of whitespace. A body of `" "` is a real body with `Content-Length: 1`. `isNotEmpty` matches what the header and cookie branches above already use.



##########
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<String> 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<String, String> headers = JMeterUtils.parseHeaders(requestHeaders);
+            for (Map.Entry<String, String> 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)) {

Review Comment:
   **The `hasCookieHeader` branch is unreachable for the shipped HTTP implementations.**
   
   `HTTPHC4Impl` and `HTTPJavaImpl` both fill `requestHeaders` from `getAllHeadersExceptCookie`, so `Cookie` is stripped by construction and the value arrives through `getCookies()` instead. `testCookieHeaderNotDuplicated` therefore pins a state that no sampler produces, which reads as coverage it is not.
   
   If some implementation does leave `Cookie` in `requestHeaders`, a comment naming it would help. Otherwise dropping the flag makes the method shorter.



##########
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<String> 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) {

Review Comment:
   **Consider moving the builder out of the GUI class.**
   
   #6375 asks for "Copy as cURL", and the follow-up most people will want is a context-menu action on the sampler itself, not only on a sample that has already run. `buildCurlCommand` has no Swing dependency, so it could live next to `BasicCurlParser` in `org.apache.jmeter.protocol.http.curl` and be reused by such an action later.
   
   That placement also enables a round-trip test the current suite cannot express: generate the command, feed it to `BasicCurlParser`, compare the parsed request against the sampler. The parser already handles `-X`, `-H`, `-b`, and `--data-raw` (`BasicCurlParser#70`, `#551-555`), so the test is cheap — and it would have caught the header and body issues above.



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

Review Comment:
   **These assertions can pass for the wrong reason.**
   
   `assertFalse(curl.contains("Connection"))` also matches the URL, so the same test against `http://connection.example.com/` fails with no regression present. The commands are short: asserting the whole string with `assertEquals` is stricter and easier to read when it breaks.
   
   Cases worth adding while you are here: repeated header names, `HEAD`, a multipart body, `X-LocalAddress`, and a whitespace-only body.



##########
xdocs/changes.xml:
##########
@@ -104,6 +104,7 @@ Summary
   <ul>
     <li><pr>6333</pr>Apply HiDPI mode automatically when setting up the GUI so JMeter looks sharp on high-resolution displays. Contributed by Gabriele Coletta (github.com/gdmg92)</li>
     <li><pr>6656</pr>Replace the previous feather icon with the new oak leaf in the JMeter logo.</li>
+    <li><issue>6375</issue>Add a <code>cURL</code> tab to the Request panel in View Results Tree, showing the sampled HTTP request as a ready-to-run <code>curl</code> command that can be copied to a console. Contributed by Oleksandr Poliakov (github.com/poliakov-alex)</li>

Review Comment:
   Agreed on `<pr>6736</pr>`. One more on the same entry: it sits under `Changes -> UI`, but the feature is HTTP-specific and only renders for `HTTPSampleResult`. `HTTP Samplers and Test Script Recorder` looks like the better home.



##########
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 <code>Host</code>) that may be added by the HTTP protocol implementation.
+For HTTP samples the Request panel also provides a <code>cURL</code> tab that renders the request as a
+ready-to-run <code>curl</code> command, so it can be copied to a console or shared with a developer.

Review Comment:
   +1, and two more things worth a sentence there.
   
   The command carries whatever the sample carried, including `Authorization` headers, cookies, and API keys. The PR description suggests sharing it with a developer, so a note that it contains credentials earns its line.
   
   Also, the new text is added without a `<p>` wrapper, so it runs into the preceding paragraph about headers added by JMeter. The surrounding text does the same, so this is a question rather than a request: keep it as is, or wrap the new sentences?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@jmeter.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(http): add cURL tab to View Results Tree Request panel [jmeter]

Posted by "milamberspace (via GitHub)" <gi...@apache.org>.
milamberspace commented on PR #6736:
URL: https://github.com/apache/jmeter/pull/6736#issuecomment-5306087515

   @vlsi You're right, I was wrong — thanks for the correction.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@jmeter.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(http): add cURL tab to View Results Tree Request panel [jmeter]

Posted by "milamberspace (via GitHub)" <gi...@apache.org>.
milamberspace commented on PR #6736:
URL: https://github.com/apache/jmeter/pull/6736#issuecomment-5306729901

   @vlsi why not, I suppose that is possible to have another PR to add support of http2 after the merges of 6736 and 6742


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@jmeter.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(http): add cURL tab to View Results Tree Request panel [jmeter]

Posted by "milamberspace (via GitHub)" <gi...@apache.org>.
milamberspace commented on code in PR #6736:
URL: https://github.com/apache/jmeter/pull/6736#discussion_r3650826320


##########
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<String> 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$

Review Comment:
   **Consider dropping `-X` for GET.** `-X` is emitted unconditionally, so a plain GET renders as `curl -X 'GET' ...`. It is harmless but noisy; most curl generators omit `-X` for a GET with no body. Consider only emitting `-X` when the method is not GET (or when a body is present).



##########
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<String> 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<String, String> headers = JMeterUtils.parseHeaders(requestHeaders);
+            for (Map.Entry<String, String> 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$

Review Comment:
   **Multipart / file-upload requests render a broken curl command.**
   
   `getQueryString()` is not the real wire body for `multipart/form-data`: it is JMeter's rendered representation, and for file uploads it contains the literal placeholder `<actual file content, not shown here>` (see `HTTPHC4Impl.writeEntityToSB` / `PostWriter`, fed into the query string at `HTTPHC4Impl#883`). Since the `Content-Type: multipart/form-data; boundary=...` header is kept and this value is emitted verbatim via `--data-raw`, a sampled file upload produces:
   
   ```
   --data-raw '...--boundary...<actual file content, not shown here>...'
   ```
   
   Pasted into a terminal this sends the placeholder text instead of the file bytes, so the request is not reproduced. This is exactly the case `RequestViewHTTP` special-cases via `isMultipart(...)`. Suggestion: detect multipart requests and either skip `--data-raw` or replace it with a short note, rather than emit a silently-wrong command.



##########
xdocs/changes.xml:
##########
@@ -104,6 +104,7 @@ Summary
   <ul>
     <li><pr>6333</pr>Apply HiDPI mode automatically when setting up the GUI so JMeter looks sharp on high-resolution displays. Contributed by Gabriele Coletta (github.com/gdmg92)</li>
     <li><pr>6656</pr>Replace the previous feather icon with the new oak leaf in the JMeter logo.</li>
+    <li><issue>6375</issue>Add a <code>cURL</code> tab to the Request panel in View Results Tree, showing the sampled HTTP request as a ready-to-run <code>curl</code> command that can be copied to a console. Contributed by Oleksandr Poliakov (github.com/poliakov-alex)</li>

Review Comment:
   This entry uses `<issue>6375</issue>` but no `<pr>` tag. Other entries in the section reference the PR number (often alongside the issue); consider adding `<pr>6736</pr>` for traceability.



##########
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 <code>Host</code>) that may be added by the HTTP protocol implementation.
+For HTTP samples the Request panel also provides a <code>cURL</code> tab that renders the request as a
+ready-to-run <code>curl</code> command, so it can be copied to a console or shared with a developer.

Review Comment:
   Nice that the doc is updated here. Consider adding one sentence noting that multipart / file-upload requests cannot be reproduced faithfully (the file content is not captured by JMeter), so users are not surprised when such a command fails — see the related note on `RequestViewCurl`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@jmeter.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(http): add cURL tab to View Results Tree Request panel [jmeter]

Posted by "milamberspace (via GitHub)" <gi...@apache.org>.
milamberspace commented on code in PR #6736:
URL: https://github.com/apache/jmeter/pull/6736#discussion_r3730733043


##########
src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatter.java:
##########
@@ -0,0 +1,267 @@
+/*
+ * 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.
+ *
+ * <p>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.</p>
+ *
+ * <p>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).</p>
+ */
+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<String> 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 = {

Review Comment:
   `BODY_PLACEHOLDERS` duplicates two literal strings that must stay in sync with `PostWriter.java:137,161` and `HTTPHC4Impl.java:1696` (verified they match today). There's no shared constant, so if either of those messages is reworded later, `containsPlaceholder()` silently stops matching and a placeholder body could reach `--data-raw` again — the exact class of bug this PR set out to fix. Not blocking, but worth extracting a shared constant at some point.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@jmeter.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(http): add cURL tab to View Results Tree Request panel [jmeter]

Posted by "poliakov-alex (via GitHub)" <gi...@apache.org>.
poliakov-alex commented on code in PR #6736:
URL: https://github.com/apache/jmeter/pull/6736#discussion_r3797052525


##########
src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatter.java:
##########
@@ -0,0 +1,268 @@
+/*
+ * 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.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;
+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.
+ *
+ * <p>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.</p>
+ *
+ * <p>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).</p>
+ */
+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<String> 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 = {
+            PostWriter.FILE_CONTENT_PLACEHOLDER,
+            PostWriter.NON_REPEATABLE_ENTITY_PLACEHOLDER
+    };
+
+    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<String[]> 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.equalsIgnoreCase(name)) {
+                    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<String[]> 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;
+            }
+            // --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$
+        }
+
+        // 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(part[0]).append(' ').append(quote(part[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<String[]> 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();
+        }

Review Comment:
   Fixed both: extractBoundary strips a quoted boundary, and parsing only runs when the body actually contains --<boundary>, otherwise it falls through to the omitted-body note. Tests: testQuotedBoundaryIsUnquotedAndParsed, testBoundaryDisagreeingWithBodyFallsBackToNote. And done on the dedup — RequestViewHTTP now calls the shared extractBoundary; its private copy is gone.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@jmeter.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(http): add cURL tab to View Results Tree Request panel [jmeter]

Posted by "poliakov-alex (via GitHub)" <gi...@apache.org>.
poliakov-alex commented on code in PR #6736:
URL: https://github.com/apache/jmeter/pull/6736#discussion_r3658788740


##########
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<String> 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<String, String> headers = JMeterUtils.parseHeaders(requestHeaders);
+            for (Map.Entry<String, String> 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$

Review Comment:
   use -F



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@jmeter.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(http): add cURL tab to View Results Tree Request panel [jmeter]

Posted by "vlsi (via GitHub)" <gi...@apache.org>.
vlsi commented on code in PR #6736:
URL: https://github.com/apache/jmeter/pull/6736#discussion_r3791675328


##########
src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatter.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.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;
+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.
+ *
+ * <p>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.</p>
+ *
+ * <p>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).</p>
+ */
+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$
+
+    /** {@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
+     * 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<String> 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 = {
+            PostWriter.FILE_CONTENT_PLACEHOLDER,
+            PostWriter.NON_REPEATABLE_ENTITY_PLACEHOLDER
+    };
+
+    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<String[]> 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.equalsIgnoreCase(name)) {
+                    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<String[]> 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()));
+        }
+
+        boolean hasCookieHeader = false;
+        for (String[] header : headers) {
+            if (emitsForm && HTTPConstants.HEADER_CONTENT_TYPE.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; 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 (!hasCookieHeader && StringUtilities.isNotEmpty(cookies)) {
+            sb.append(NEWLINE).append("-b ").append(quote(cookies)); //$NON-NLS-1$
+        }
+
+        if (emitsForm) {
+            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$
+        } 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<String[]> parseMultipartForm(String contentType, String body) {
+        String boundary = extractBoundary(contentType);
+        // 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);
+        try {
+            multipart.parseArguments(body);
+        } catch (RuntimeException e) { // NOSONAR malformed body: fall back to the omitted-body note
+            return List.of();
+        }
+        List<String[]> parts = new ArrayList<>();
+        for (JMeterProperty property : multipart.getArguments()) {
+            parts.add(formField((HTTPArgument) property.getObjectValue()));
+        }
+        for (HTTPFileArg file : multipart.getHTTPFileArgs().asArray()) {
+            parts.add(fileField(file));
+        }
+        return parts;
+    }
+
+    /**
+     * 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[] 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) {

Review Comment:
   Deduplicating this was the right call, and `RequestViewHTTP` got better for it. Two things follow from it now being public.
   
   It dereferences `contentType` with no null check, which was safe while it was private and reached only through an `isMultipart` guard. As published API it is worth a guard or an `@throws`.
   
   `RequestViewHTTP` now depends on `CurlCommandFormatter` to parse a MIME header, which is a strange direction — nothing about a boundary is curl-specific. `MultipartUrlConfig` is the only consumer of the result in both call sites and would be a more natural home.



##########
src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatter.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.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;
+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.
+ *
+ * <p>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.</p>
+ *
+ * <p>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).</p>
+ */
+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$
+
+    /** {@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
+     * 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<String> 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 = {
+            PostWriter.FILE_CONTENT_PLACEHOLDER,
+            PostWriter.NON_REPEATABLE_ENTITY_PLACEHOLDER
+    };
+
+    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<String[]> 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.equalsIgnoreCase(name)) {
+                    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<String[]> 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()));
+        }
+
+        boolean hasCookieHeader = false;
+        for (String[] header : headers) {
+            if (emitsForm && HTTPConstants.HEADER_CONTENT_TYPE.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; 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 (!hasCookieHeader && StringUtilities.isNotEmpty(cookies)) {
+            sb.append(NEWLINE).append("-b ").append(quote(cookies)); //$NON-NLS-1$
+        }
+
+        if (emitsForm) {
+            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$
+        } 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<String[]> parseMultipartForm(String contentType, String body) {
+        String boundary = extractBoundary(contentType);
+        // 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);
+        try {
+            multipart.parseArguments(body);
+        } catch (RuntimeException e) { // NOSONAR malformed body: fall back to the omitted-body note
+            return List.of();
+        }
+        List<String[]> parts = new ArrayList<>();
+        for (JMeterProperty property : multipart.getArguments()) {
+            parts.add(formField((HTTPArgument) property.getObjectValue()));
+        }
+        for (HTTPFileArg file : multipart.getHTTPFileArgs().asArray()) {
+            parts.add(fileField(file));
+        }
+        return parts;

Review Comment:
   The original interleaving of fields and files is still lost — all `--form-string` parts are emitted, then all `-F` parts, whatever order the body had. Carrying it over from the resolved thread since the content-type half was fixed and this half was not.
   
   Rarely load-bearing, and the two-loop shape is a consequence of `MultipartUrlConfig` keeping arguments and files in separate collections, so "won't fix, it is documented" is a fine answer — just not silence.



##########
src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatter.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.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;
+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.
+ *
+ * <p>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.</p>
+ *
+ * <p>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).</p>
+ */
+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$
+
+    /** {@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
+     * 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<String> 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 = {
+            PostWriter.FILE_CONTENT_PLACEHOLDER,
+            PostWriter.NON_REPEATABLE_ENTITY_PLACEHOLDER
+    };
+
+    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<String[]> 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.equalsIgnoreCase(name)) {
+                    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<String[]> 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()));
+        }
+
+        boolean hasCookieHeader = false;
+        for (String[] header : headers) {
+            if (emitsForm && HTTPConstants.HEADER_CONTENT_TYPE.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; 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 (!hasCookieHeader && StringUtilities.isNotEmpty(cookies)) {
+            sb.append(NEWLINE).append("-b ").append(quote(cookies)); //$NON-NLS-1$
+        }
+
+        if (emitsForm) {
+            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$
+        } 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<String[]> parseMultipartForm(String contentType, String body) {
+        String boundary = extractBoundary(contentType);
+        // 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);
+        try {
+            multipart.parseArguments(body);
+        } catch (RuntimeException e) { // NOSONAR malformed body: fall back to the omitted-body note
+            return List.of();
+        }

Review Comment:
   **A file part with no `Content-Type` discards the whole multipart rendering, fields and all.**
   
   `MultipartUrlConfig#162` passes the part's content type straight into `files.addHTTPFileArg(path, name, contentType)`, and `HTTPFileArg#82` rejects a null mime type with `IllegalArgumentException("Parameters must not be null")`. A file part that carries no `Content-Type` header therefore throws mid-parse, this catch swallows it, and everything already parsed — every plain text field in the body — is dropped along with it. Observed on this branch:
   
   ```
   body: --xyz
         Content-Disposition: form-data; name="upload"; filename="report.pdf"
   
         <actual file content, not shown here>
         --xyz--
   
   curl -X 'POST' \
     'http://example.com/upload' \
     -H 'Content-Type: multipart/form-data; boundary=xyz'
   # Request body cannot be reproduced: …
   ```
   
   The file name and every field were recoverable; the note claims otherwise. Defaulting the mime type to `""` before constructing the arg is enough, and narrowing the catch would stop the next such case hiding the same way — a blanket `RuntimeException` around a parser is what turned this into a silent degradation rather than a visible one.
   
   Not this PR's bug, but adjacent and worth knowing: `RequestViewHTTP#219` runs the same `parseArguments` call with no catch at all, so the same body makes the HTTP tab throw instead.



##########
src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatterTest.java:
##########
@@ -0,0 +1,367 @@
+/*
+ * 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"
+                + "<actual file content, not shown here>\r\n"
+                + "--xyz--\r\n");
+
+        String curl = CurlCommandFormatter.format(res);
+        // 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.
+        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");
+        res.setRequestHeaders("Content-Type: application/octet-stream");
+        res.setQueryString("<actual file content, not shown here>");
+
+        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("<Entity was not repeatable, cannot view what was sent>");
+
+        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);
+        // 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
+    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<String> 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<String> 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);
+    }
+
+    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<actual file content, not shown here>\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<actual file content, not shown here>\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());
+    }

Review Comment:
   **This is the test that should have caught the `-F` quoting problem, and it cannot.**
   
   `assertFalse(parsed.getFormData().isEmpty())` passes for any non-empty result, including `FileArgumentHolder(report.pdf", {type=application/pd})`. The field half is checked by name and value; the file half, which is the part the last round changed, is checked only for existence.
   
   Asserting the parsed name and type would close it:
   
   ```java
   assertTrue(parsed.getFormData().stream()
           .anyMatch(e -> "upload".equals(e.getKey())
                   && "report.pdf".equals(e.getValue().getName())),
           parsed.getFormData().toString());
   ```
   
   Same shape as the assertion you already wrote for `comment`. A round trip asserted only for non-emptiness tests that the parser did not crash, which is a weaker claim than the test name makes.



##########
src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatter.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.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;
+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.
+ *
+ * <p>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.</p>
+ *
+ * <p>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).</p>
+ */
+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$
+
+    /** {@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
+     * 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<String> 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 = {
+            PostWriter.FILE_CONTENT_PLACEHOLDER,
+            PostWriter.NON_REPEATABLE_ENTITY_PLACEHOLDER
+    };
+
+    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<String[]> 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.equalsIgnoreCase(name)) {
+                    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<String[]> 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()));
+        }
+
+        boolean hasCookieHeader = false;
+        for (String[] header : headers) {
+            if (emitsForm && HTTPConstants.HEADER_CONTENT_TYPE.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; 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 (!hasCookieHeader && StringUtilities.isNotEmpty(cookies)) {
+            sb.append(NEWLINE).append("-b ").append(quote(cookies)); //$NON-NLS-1$
+        }
+
+        if (emitsForm) {
+            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$
+        } 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<String[]> parseMultipartForm(String contentType, String body) {
+        String boundary = extractBoundary(contentType);
+        // 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);
+        try {
+            multipart.parseArguments(body);
+        } catch (RuntimeException e) { // NOSONAR malformed body: fall back to the omitted-body note
+            return List.of();
+        }
+        List<String[]> parts = new ArrayList<>();
+        for (JMeterProperty property : multipart.getArguments()) {
+            parts.add(formField((HTTPArgument) property.getObjectValue()));
+        }
+        for (HTTPFileArg file : multipart.getHTTPFileArgs().asArray()) {
+            parts.add(fileField(file));
+        }
+        return parts;
+    }
+
+    /**
+     * 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[] 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$
+    }

Review Comment:
   **The double-quoted path is not readable by `BasicCurlParser`, so the command no longer round-trips.**
   
   This closes the curl side of the `;`/`,` problem — I verified curl accepts `-F 'up=@"a;b,c.txt";type=text/plain'`. But this class documents itself as "the reverse of what `BasicCurlParser` does", and the parser cannot read the form it now emits.
   
   `BasicCurlParser#729` takes everything after `@` and hands it to `unquote`, which assumes a value starting with `"` also *ends* with `"` (`BasicCurlParser#982`: `value.substring(1, value.length() - 1)`). With a `;type=` suffix after the closing quote it strips the wrong last character, and `ArgumentHolder.parse` then splits what is left. Fed the output of this branch:
   
   ```
   -F 'upload=@"report.pdf";type=application/pdf'
     → FileArgumentHolder(report.pdf", {type=application/pd})
   ```
   
   A stray quote on the name, and the last character of the MIME type eaten. For the name this quoting was introduced to protect it is worse — `a;b,c.txt` leaves the segment `b,c.txt"` with no `=` in it, and `ArgumentHolder#47-48` reads `typeParts[1]` unconditionally, so the import throws `ArrayIndexOutOfBoundsException`.
   
   Two shapes still work, which is why nothing failed: a quoted path with no `;type=` suffix, and any `-F` whose value does not start with `@` (the typed text fields go down that branch and round-trip cleanly).
   
   The fix belongs in the parser rather than here: split the `;` options off before unquoting, so `@"name";type=x` reads the way curl reads it. That keeps both directions honest and is in scope given the PR already touches `RequestViewHTTP` and `PostWriter`. Quoting only when the path actually contains `;` or `,` would restore the common case but leave the rare one broken in both tools.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@jmeter.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(http): add cURL tab to View Results Tree Request panel [jmeter]

Posted by "milamberspace (via GitHub)" <gi...@apache.org>.
milamberspace commented on PR #6736:
URL: https://github.com/apache/jmeter/pull/6736#issuecomment-5306597157

   While testing, I noticed that this PR (#6736 , cURL request view) and #6742 (HttpClient5 sampler with HTTP/2 support) are somewhat related.
   
   I checked out both PRs together on a temporary branch and ran an HTTP/2 request. As expected, the generated cURL command does not include --http2 (nor  --http2-prior-knowledge). Likewise, forcing an HTTP/1.1 request does not emit --http1.1.
   
   This is normal: #6736 currently has no knowledge of #6742.
   
   @vlsi  + @poliakov-alex : would you be OK with linking these two PRs? If so, my suggestion would be:
   1. Merge #6742 first, after a positive review (@vlsi).
   2. Then update #6736 to emit the proper --http2 / --http2-prior-knowledge / --http1.1 flags based on the sampler's protocol setting (@poliakov-alex )
   3. Merge #6736 after review (@vlsi + me).
   
   These 2 PRs would bring some very nice new capabilities to JMeter 6.
   (cc @andreaslind01 )


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@jmeter.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(http): add cURL tab to View Results Tree Request panel [jmeter]

Posted by "milamberspace (via GitHub)" <gi...@apache.org>.
milamberspace commented on PR #6736:
URL: https://github.com/apache/jmeter/pull/6736#issuecomment-5080127554

   Nice feature — the implementation closely follows the existing `RequestViewHTTP` sibling and is well covered by tests. A few points from a review:
   
   ### Multipart / file-upload requests produce a broken curl command
   
   The `--data-raw` block uses `HTTPSampleResult.getQueryString()` as the body. For `multipart/form-data` requests that value is not the real wire body — it's JMeter's rendered representation, and for file uploads it contains the literal placeholder `<actual file content, not shown here>` (see `HTTPHC4Impl.writeEntityToSB` / `PostWriter`, fed into the query string at `HTTPHC4Impl#883`).
   
   Because the `Content-Type: multipart/form-data; boundary=…` header is kept while the body is emitted verbatim via `--data-raw`, a sampled file upload renders as:
   
   ```
   curl -X 'POST' \
     'https://example.com/upload' \
     -H 'Content-Type: multipart/form-data; boundary=...' \
     --data-raw '...--boundary...<actual file content, not shown here>...'
   ```
   
   Pasted into a terminal this sends the placeholder text instead of the file bytes, so the request is not reproduced. This is exactly the case `RequestViewHTTP` special-cases via `isMultipart(...)`; that handling is missing here. Suggestion: detect multipart requests and either skip `--data-raw` or replace it with a short note, rather than emit a silently-wrong command.
   
   ### Document the multipart limitation
   
   The PR already updates `component_reference.xml` with a paragraph about the cURL tab 👍 — it would be worth adding one sentence there noting that multipart / file-upload requests cannot be reproduced faithfully (the file content is not captured by JMeter), so users aren't surprised.
   
   ### Drop `-X` for GET requests
   
   `-X` is emitted unconditionally, so a plain GET renders as `curl -X 'GET' …`. It's harmless but noisy; most curl generators omit `-X` for a GET with no body. Consider only emitting `-X` when the method is not GET (or when a body is present).
   
   ### changes.xml: reference the PR
   
   The `changes.xml` entry uses `<issue>6375</issue>` but no `<pr>` tag. Other entries in the section reference the PR number (often alongside the issue) — adding `<pr>6736</pr>` would improve traceability.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@jmeter.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(http): add cURL tab to View Results Tree Request panel [jmeter]

Posted by "vlsi (via GitHub)" <gi...@apache.org>.
vlsi commented on code in PR #6736:
URL: https://github.com/apache/jmeter/pull/6736#discussion_r3786646039


##########
src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatter.java:
##########
@@ -0,0 +1,268 @@
+/*
+ * 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.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;
+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.
+ *
+ * <p>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.</p>
+ *
+ * <p>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).</p>
+ */
+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<String> 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 = {
+            PostWriter.FILE_CONTENT_PLACEHOLDER,
+            PostWriter.NON_REPEATABLE_ENTITY_PLACEHOLDER
+    };
+
+    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<String[]> 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.equalsIgnoreCase(name)) {
+                    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<String[]> 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;
+            }
+            // --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$
+        }
+
+        // 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(part[0]).append(' ').append(quote(part[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<String[]> 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();
+        }

Review Comment:
   **A quoted or mismatched boundary yields a corrupted `--form-string`, not the omitted-body note.**
   
   `extractBoundary` (line 235) returns the boundary with its quotes still attached, so `Content-Type: multipart/form-data; boundary="xyz"` gives `"xyz"`. `MultipartUrlConfig.parseArguments` then splits on `--"xyz"`, finds no delimiter, and treats the whole body as one part. That part does contain `Content-Disposition: form-data`, so a field is created, and its value runs to `part.lastIndexOf(CRLF)` (`MultipartUrlConfig#170`) — i.e. it swallows the trailing boundary marker.
   
   Rendered on this branch:
   
   ```
   Content-Type: multipart/form-data; boundary="xyz"
   body: --xyz\r\nContent-Disposition: form-data; name="a"\r\n\r\nb\r\n--xyz--\r\n
   
   curl -X 'POST' \
     'http://example.com/upload' \
     --form-string 'a=b
   --xyz--'
   ```
   
   The same thing happens whenever the header boundary and the body disagree: `boundary=nomatch` over a body delimited by `--other` renders `--form-string 'a=b\n--other--'`. Both commands run and send garbage — the class of bug this PR set out to remove.
   
   Quoting is legal per RFC 2046, and both cases are reachable: when `getUseMultipart()` is false, `HTTPHC4Impl#1523` keeps the user's own `Content-Type` header, so a hand-built multipart body in the Body Data tab arrives here verbatim.
   
   Two small guards fix it: strip surrounding quotes in `extractBoundary`, and check that the body actually contains `--<boundary>` before parsing, falling through to the omitted-body branch when it does not.
   
   While you are in `extractBoundary` — it now duplicates `RequestViewHTTP#251`, and the new one is the better of the two (it returns `null` when `boundary=` is absent, where the old one builds a nonsense substring). Now that the logic is Swing-free, `RequestViewHTTP` could call it instead.



##########
src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatter.java:
##########
@@ -0,0 +1,268 @@
+/*
+ * 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.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;
+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.
+ *
+ * <p>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.</p>
+ *
+ * <p>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).</p>
+ */
+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<String> 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 = {
+            PostWriter.FILE_CONTENT_PLACEHOLDER,
+            PostWriter.NON_REPEATABLE_ENTITY_PLACEHOLDER
+    };
+
+    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<String[]> 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.equalsIgnoreCase(name)) {
+                    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<String[]> 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;
+            }
+            // --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$
+        }
+
+        // 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(part[0]).append(' ').append(quote(part[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<String[]> 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<String[]> 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$
+        }
+        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$
+        }

Review Comment:
   **A file name containing `;` or `,` produces a `-F` spec curl rejects.**
   
   The spec is concatenated unquoted, so a part named `a;b,c.txt` renders as `-F 'up=@a;b,c.txt;type=text/plain'`. curl parses `;` and `,` inside the argument itself, so shell quoting does not protect it — the same shape as the `@`-prefixed value that `--form-string` solved, but on the file side:
   
   ```console
   $ curl -F 'up=@a;b,c.txt;type=text/plain' http://…
   curl: (26) Failed to open/read local data from file/application
   
   $ curl -F 'up=@"a;b,c.txt";type=text/plain' http://…
   # exit 0, part sent as filename="a;b,c.txt"
   ```
   
   Commas in file names are common enough to hit this in practice. Wrapping the path in double quotes inside the spec — `name=@"path"`, with `;type=` after the closing quote — fixes both characters.



##########
src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatter.java:
##########
@@ -0,0 +1,268 @@
+/*
+ * 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.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;
+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.
+ *
+ * <p>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.</p>
+ *
+ * <p>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).</p>
+ */
+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<String> 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 = {
+            PostWriter.FILE_CONTENT_PLACEHOLDER,
+            PostWriter.NON_REPEATABLE_ENTITY_PLACEHOLDER
+    };
+
+    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<String[]> 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.equalsIgnoreCase(name)) {
+                    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<String[]> 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;
+            }
+            // --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$
+        }
+
+        // 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$
+        }

Review Comment:
   **A correction to my earlier note, and a narrow case it leaves open.**
   
   I said the `hasCookieHeader` guard was unreachable, and that was too broad. It holds for `HTTPHC4Impl` and `HTTPJavaImpl`, which strip `Cookie` in `getAllHeadersExceptCookie`, but `AjpSampler.setConnectionHeaders` copies Header Manager entries into the header string verbatim while `setConnectionCookies` fills `getCookies()` separately. With both a Header Manager `Cookie` and a Cookie Manager, the result is:
   
   ```
   curl \
     'http://example.com/' \
     -H 'Cookie: a=1' \
     -b 'b=2'
   ```
   
   curl lets the explicit header win, so `b=2` is dropped without a word. Skipping `-b` when a `Cookie` header was already emitted restores what the guard used to cover. Low stakes given it is AJP-only — mentioning it because I am the reason the guard went away.



##########
src/protocol/http/src/test/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatterTest.java:
##########
@@ -0,0 +1,257 @@
+/*
+ * 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"
+                + "<actual file content, not shown here>\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);
+        // 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");
+        res.setRequestHeaders("Content-Type: application/octet-stream");
+        res.setQueryString("<actual file content, not shown here>");
+
+        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("<Entity was not repeatable, cannot view what was sent>");
+
+        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);
+        // --compressed makes curl send its own Accept-Encoding, so the explicit one is dropped.
+        assertFalse(curl.contains("-H 'Accept-Encoding"), 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<String> headers = parsed.getHeaders().stream()
+                .map(e -> e.getKey() + ": " + e.getValue())
+                .collect(Collectors.toList());
+        assertEquals(List.of("X-A: 1", "X-B: 2"), headers);
+    }

Review Comment:
   **The round-trip tests stop short of the flags this class now emits.**
   
   `BasicCurlParser` already handles `--head`, `--compressed`, `-F`, and `--form-string` (`BasicCurlParser#537,557,560,614`), so the round trip can cover the interesting paths rather than the simple one. That is the cheapest guard against the multipart and encoding notes above regressing later.
   
   Cases the suite does not reach today, each of which renders a wrong command on this branch: a quoted boundary, a boundary that disagrees with the body, a file name containing `;` or `,`, and a part carrying a non-default content type.



##########
src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatter.java:
##########
@@ -0,0 +1,268 @@
+/*
+ * 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.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;
+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.
+ *
+ * <p>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.</p>
+ *
+ * <p>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).</p>
+ */
+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<String> 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 = {
+            PostWriter.FILE_CONTENT_PLACEHOLDER,
+            PostWriter.NON_REPEATABLE_ENTITY_PLACEHOLDER
+    };
+
+    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<String[]> 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.equalsIgnoreCase(name)) {
+                    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<String[]> 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;
+            }
+            // --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$
+        }
+
+        // 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(part[0]).append(' ').append(quote(part[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<String[]> 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<String[]> 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$
+        }

Review Comment:
   **The per-part `Content-Type` is dropped.**
   
   `MultipartUrlConfig` already parses it into the argument (`MultipartUrlConfig#119,174`), and it is user-settable: the Parameters table has a content-type column (`HTTPArgumentsPanel#55,66`), and `HTTPHC4Impl` builds each part as `StringBody(value, contentType)` from it. `--form-string` emits no part header at all — verified against a server:
   
   ```
   Content-Disposition: form-data; name="meta"
                                                 ← no Content-Type
   {"a":1}
   ```
   
   A field explicitly marked `application/json` therefore arrives with curl's default. `--form-string` cannot carry `;type=` by design, so the choices are to use `-F 'name=value;type=…'` when the part has a non-default type and the value does not start with `@` or `<`, or to state the limitation in `component_reference.xml`. Either is fine; silently losing it is the part worth changing.
   
   Two smaller things in the same loop: the original interleaving of fields and files is lost (all `--form-string` first, then all `-F`), and a part with no blank-line separator renders as `--form-string 'a='` with the value silently gone.



##########
src/core/src/main/resources/org/apache/jmeter/resources/messages.properties:
##########
@@ -1456,6 +1456,8 @@ 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

Review Comment:
   This reads as a fragment glued to a finite clause — "Request body not shown (…) and cannot be reproduced". Since it renders as a shell comment the user reads next to the command, reason-then-consequence is easier to scan:
   
   ```properties
   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
   ```



##########
src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/curl/CurlCommandFormatter.java:
##########
@@ -0,0 +1,268 @@
+/*
+ * 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.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;
+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.
+ *
+ * <p>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.</p>
+ *
+ * <p>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).</p>
+ */
+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<String> 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 = {
+            PostWriter.FILE_CONTENT_PLACEHOLDER,
+            PostWriter.NON_REPEATABLE_ENTITY_PLACEHOLDER
+    };
+
+    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<String[]> 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.equalsIgnoreCase(name)) {
+                    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<String[]> 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;
+            }
+            // --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$
+        }
+
+        // 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$
+        }

Review Comment:
   **Dropping the explicit `Accept-Encoding` changes what the server is asked for.**
   
   `--compressed` is the right flag to add — JMeter does decode the response, so the command should too. But it is not a substitute for the header, because curl supplies its own list when none is given, and that list depends on how curl was built:
   
   ```console
   $ curl --compressed http://…
   Accept-Encoding: deflate, gzip                 # this build; brotli/zstd builds also send br, zstd
   
   $ curl --compressed -H 'Accept-Encoding: gzip' http://…
   Accept-Encoding: gzip                          # explicit header wins, response still decoded
   ```
   
   So the two are not redundant: keeping both reproduces the request byte-for-byte *and* decodes, while dropping the header lets curl negotiate an encoding the test plan never asked for, and the server may answer with a different body than the sample recorded.
   
   Suggest keeping the header and adding `--compressed` alongside it. `testAcceptEncodingAddsCompressed` asserts the current behavior, so its second assertion inverts with the fix.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@jmeter.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(http): add cURL tab to View Results Tree Request panel [jmeter]

Posted by "vlsi (via GitHub)" <gi...@apache.org>.
vlsi commented on PR #6736:
URL: https://github.com/apache/jmeter/pull/6736#issuecomment-5306620085

   As for me, the first PR that gets to mergeable shape merges the first.
   Typically, smaller PRs like the current one are easier to review and merge, so I would rather consider 6736 -> 6742.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@jmeter.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(http): add cURL tab to View Results Tree Request panel [jmeter]

Posted by "poliakov-alex (via GitHub)" <gi...@apache.org>.
poliakov-alex commented on PR #6736:
URL: https://github.com/apache/jmeter/pull/6736#issuecomment-5119979141

   > Thanks for this, @poliakov-alex — really nice work. `CurlCommandFormatter` is kept Swing-free and reusable, the test coverage on the tricky cases is excellent, and I appreciate the care around the curl pitfalls (`--head` vs `-X HEAD`, `-X GET` to keep the method, `--data-raw` instead of `--data`, hop-by-hop headers dropped, and the security note in the docs).
   > 
   > One correctness issue I'd like fixed before merge, plus a couple of minor notes.
   > 
   > ### Must fix — regular multipart fields should use `--form-string`
   > In `parseMultipartForm` the non-file fields are emitted as `-F 'name=value'`:
   > 
   > ```java
   > parts.add(argument.getName() + "=" + argument.getValue()); // -> -F 'name=value'
   > ```
   > 
   > curl gives special meaning to a `-F` **value** that starts with `@` or `<`: `@` reads a file to upload, `<` reads a file's contents as the field value. So a legitimate text field whose value begins with `@` or `<` (e.g. `handle=@someuser`, `xml=<root/>`) is silently misinterpreted — curl tries to open a file, or fails. Shell single-quoting does not protect against this, because it is curl itself (not the shell) doing the interpretation.
   > 
   > Please emit regular fields with `--form-string 'name=value'` (verbatim value, no `@`/`<` handling) and keep `-F 'name=@path;type=...'` only for the file parts. This mirrors the reasoning you already applied when choosing `--data-raw` over `--data`.
   > 
   > ### Minor (non-blocking)
   > * **Redundant `--compressed` + explicit `Accept-Encoding`**: when `--compressed` is emitted, curl sends its own `Accept-Encoding`, so the explicit `-H 'Accept-Encoding: ...'` is redundant. Harmless, but you could drop the header when emitting `--compressed`.
   > * **Tab order**: only the Raw tab is pinned first in `RequestPanel`; the HTTP↔cURL order comes from `ServiceLoader` and isn't deterministic, so "next to Raw and HTTP" is best-effort. Nothing to change in the PR — just noting it.
   > * **PR description nit**: the description mentions `RequestViewCurlTest` (8 tests) but the file is `CurlCommandFormatterTest` (15 tests).
   > 
   > Once the `--form-string` change is in (ideally with a test for a field value starting with `@`), this looks good to merge.
   
   Added commit, please check


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@jmeter.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org