HTTP发布请求的Java代码,以将两个(证书和certificateKey)文件作为多部分形式数据发送

时间:2019-06-20 05:46:35

标签: java apache api http multipartform-data

我需要使用JAVA发送两个带有后期处理请求的文件作为多部分表单数据,并且此代码我收到了BAD REQUEST 400。

RESPONSE I GET -- 
{
  "status" : "BAD_REQUEST",
  "message" : "Failed to parse multipart servlet request; nested exception is java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found",
  "errors" : null,
  "timestamp" : "2019-06-20 05:48:31"
}

为此,我使用了Apache HttpComponents

File certFile = new File("/home/vijay/Downloads/facilio.crt");
    FileBody data = new FileBody(certFile);

    File keyFile = new File("/home/vijay/Downloads/facilio-private.key");
    FileBody data2 = new FileBody(keyFile);

    HttpClient httpclient = new DefaultHttpClient();
    String authString = username + ":" + password;
    System.out.println("auth string: " + authString);
    byte[] authEncBytes =Base64.getEncoder().encode(authString.getBytes());
    String authStringEnc = new String(authEncBytes);
    System.out.println("Base64 encoded auth string: " + authStringEnc);
    HttpPost httpPost = new HttpPost("https://api.xxxx/xxx/xxx");
    httpPost.addHeader(HttpHeaders.AUTHORIZATION, "Basic "+authStringEnc);
    // httpPost.addHeader("Accept", "application/json");
    System.out.println(" content type -"+ContentType.MULTIPART_FORM_DATA.getMimeType());
    httpPost.addHeader(HttpHeaders.CONTENT_TYPE,ContentType.MULTIPART_FORM_DATA.getMimeType());



    MultipartEntity reqEntity = new MultipartEntity();
    MultipartEntity reqEntity1 = new MultipartEntity();

    reqEntity.addPart("certificate", data);
    reqEntity1.addPart("ceritificateKey",data2);
    httpPost.setEntity(reqEntity);
    httpPost.setEntity(reqEntity1);
    try {
        HttpResponse response = httpclient.execute(httpPost);
        System.out.println("code-------"+response.getStatusLine().getStatusCode());
        System.out.println(response.toString());
        HttpEntity ent = response.getEntity();
        InputStream is = ent.getContent();
        InputStreamReader isr = new InputStreamReader(is);
        int numCharsRead;
        char[] charArray = new char[1024];
        StringBuffer sb = new StringBuffer();
        while ((numCharsRead = isr.read(charArray)) > 0) {
            sb.append(charArray, 0, numCharsRead);
        }
        String result = sb.toString();

        System.out.println("*** BEGIN ***");
        System.out.println(result);
        System.out.println("*** END ***");

    } catch (IOException e) {
        e.printStackTrace();
    }

我应该得到200的响应字符串。任何建议或代码审查将不胜感激。预先感谢

1 个答案:

答案 0 :(得分:0)

不确定是代码中唯一的问题,但是MultipartEntity顾名思义,它包含一个多部分实体。您只需一个请求即可

MultipartEntity reqEntity = new MultipartEntity();

reqEntity.addPart("certificate", data);
reqEntity.addPart("ceritificateKey",data2);
httpPost.setEntity(reqEntity);