자바를 사용하여 폼 데이터의 업로드 파일

폴 :

나는 아파치 API를 사용하여 Java에서 HTTP POST 요청을 수행하려합니다.

이 같은 컬 요청 외모로

curl https://host/upload
-X POST
-H "Authorization: Bearer xxx"
-H "Content-Type: multipart/form-data"
-H "Accept: application/json"
-F "file=@{PathToImage}" -F "type=file" 

이 작품의 벌금 컬을 실행할 때 동안 다음과 같은 자바 코드를 실행할 때 서버는 500er 결과를 반환

    final HttpPost httppost = new HttpPost("https://host/upload");
    httppost.addHeader("Authorization", "Bearer xxx");
    httppost.addHeader("Accept", "application/json");
    httppost.addHeader("Content-Type", "multipart/form-data");

    final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    final File file = new File("c:\\tmp\\myfile.pdf");
    builder.addBinaryBody("file", file);
    builder.addTextBody("type", "file");
    final HttpEntity entity = builder.build();
    httppost.setEntity(entity);
    final HttpResponse response = httpclient.execute(httppost);
    httpclient.close();

내가 여기에 놓친 거지 어떤 생각?

C. 스미스 :

질문은 비슷합니다. 하지만 대답은 addPart로 addBinary을 변경 믿습니다.

final HttpPost httppost = new HttpPost("https://host/upload");
httppost.addHeader("Authorization", "Bearer xxx");
httppost.addHeader("Accept", "application/json");
httppost.addHeader("Content-Type", "multipart/form-data");

final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
final File file = new File("c:\\tmp\\myfile.pdf");
builder.addPart("file", new FileBody(file));
builder.addTextBody("type", "file");
final HttpEntity entity = builder.build();
httppost.setEntity(entity);
final HttpResponse response = httpclient.execute(httppost);
httpclient.close();

추천

출처http://43.154.161.224:23101/article/api/json?id=329827&siteId=1