有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java中curl命令的等价物

我想要一些帮助,用java编写与下面的curl命令等效的代码

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --header  'cookie: [APP COOKIES];' -d 'sampleFile.json' 'https://url.com'

共 (1) 个答案

  1. # 1 楼答案

    使用apache的HttpClient,您可以执行以下操作:

    ...
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.entity.UrlEncodedFormEntity
    import org.apache.http.Consts;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.HttpEntity;
    ....
    
    public String sendPost(String url, Map<String, String> postParams, 
            Map<String, String> header, String cookies) {
    
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> formParams = new ArrayList<NameValuePair>();
        HttpClientBuilder clientBuilder = HttpClients.createDefault();
        CloseableHttpClient httpclient = clientBuilder.build();
    
        if (header != null) {
            Iterator<Entry<String, String>> itCabecera = header.entrySet().iterator();
            while (itCabecera.hasNext()) {
                Entry<String, String> entry = itCabecera.next();
    
                httpPost.addHeader(entry.getKey(), entry.getValue());
            }
        }
    
        httpPost.setHeader("Cookie", cookies);
    
        if (postParams != null) {
            Iterator<Entry<String, String>> itParms = postParams.entrySet().iterator();
            while (itParms.hasNext()) {
                Entry<String, String> entry = itParms.next();
    
                formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
    
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formParams, Consts.UTF_8);
        httpPost.setEntity(formEntity);
    
        CloseableHttpResponse httpResponse = httpclient.execute(httpPost);
    
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
            pageContent = EntityUtils.toString(entity);
        }
    
        return pageContent;
    }
    

    我希望这对你有帮助

    编辑:

    我添加了发送文件的方式。我输入了一个单独的代码,以避免混合代码(这是一个近似值,基于this examples):

    File file = new File("path/to/file");
    String message = "This is a multipart post";
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    
    if (postParams != null) {
        Iterator<Entry<String, String>> itParms = postParams.entrySet().iterator();
        while (itParms.hasNext()) {
            Entry<String, String> entry = itParms.next();
    
            builder.addTextBody(entry.getKey(), entry.getValue(), ContentType.DEFAULT_BINARY);
        }
    }
    
    builder.addTextBody("text", message, ContentType.DEFAULT_BINARY);
    
    HttpEntity entity = builder.build();
    httpPost.setEntity(entity);