如何将此curl请求转换为Http post请求,以便在java中上载文件?

如何将此curl请求转换为Http post请求,以便在java中上载文件?,java,rest,curl,Java,Rest,Curl,以下是我的要求: curl -X POST --data-urlencode 'data1@/Users/Documents/file.csv' http://localhost:8000/predict 下面是我的等效Java实现 String filePath = inputFilePath; String url = inputUrl; File file = new File(filePath); CloseableHttpClient

以下是我的要求:

curl -X POST --data-urlencode 'data1@/Users/Documents/file.csv' http://localhost:8000/predict
下面是我的等效Java实现

String filePath = inputFilePath;
        String url = inputUrl;
        File file = new File(filePath);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost uploadFile = new HttpPost(inputUrl);
        uploadFile.addHeader("content-type", "application/x-www-form-urlencoded;charset=utf-8");

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();

        FileBody fileBody = new FileBody(new File(inputFilePath));

        HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("data1", fileBody)
                .build();


        uploadFile.setEntity(reqEntity);
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(uploadFile);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
我试图从JavaHTTPPOST调用我的R RESTAPI端点

#* @post /predict
mypredict <- function(data1) {
  print(data1)

}
#*@post/predict

mypredict指定内容类型
application/x-www-form-urlencoded
(就像curl在本例中所做的那样),但提供了一个与
多部分/表单数据
相对应的实际主体(实体)。相反,请使用
URLEncodedFormEntity
包含一个
NameValuePair
如下内容:

byte[] contents = Files.readAllBytes (new File(filepath).toPath());
List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
list.add(new BasicNameValuePair("data1", new String(contents,charset));
uploadFile.setEntity(new UrlEncodedFormEntity (list));
byte[]contents=Files.readAllBytes(新文件(filepath.toPath());
列表=新的ArrayList();
添加(新的BasicNameValuePair(“data1”,新字符串(内容,字符集));
setEntity(新的UrlEncodedFormEntity(列表));
您不需要
addHeader(“content-type”,…)
,因为设置实体会自动提供content-type头(和content-length)

byte[] contents = Files.readAllBytes (new File(filepath).toPath());
List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
list.add(new BasicNameValuePair("data1", new String(contents,charset));
uploadFile.setEntity(new UrlEncodedFormEntity (list));