如何在Java中正确更改http请求的内容类型?

时间:2019-01-17 14:39:16

标签: java request

我有以下代码可以使用servicenow API上传附件:

public static void main(String[] args) {
  try {

                  //Add needed headers
                  Header header = new BasicHeader(HttpHeaders.CONTENT_TYPE, "image/jpeg");
                  Header header2 = new BasicHeader(HttpHeaders.ACCEPT, "application/json");
                  List<Header> headers = new ArrayList<Header>();
                  headers.add(header);
                  headers.add(header2);

                  //Add credential
              CredentialsProvider provider = new BasicCredentialsProvider();
                  UsernamePasswordCredentials credentials     = new UsernamePasswordCredentials("yourUserName", "yourPassword");
                  provider.setCredentials(AuthScope.ANY, credentials);
                  CloseableHttpClient client = HttpClientBuilder.create()
                                                                          .setDefaultCredentialsProvider(provider)
                                                                          .setDefaultHeaders(headers)
                                                                          .build();

                  HttpPost post = new HttpPost("https://yourInstanceName/api/now/attachment/file?table_name=incident&table_sys_id=c8c3ba6643333a4073a1433e0210c706&file_name=Tulips.jpg");
                  String textFileName = "C:/Users/Public/Pictures/Sample Pictures/Tulips.jpg";
                  byte[] fileBytes = getBytes(textFileName);
                  post.setEntity(new ByteArrayEntity(fileBytes));
                  ResponseHandler<String> responseHandler=new BasicResponseHandler();
                  String responseBody = client.execute(post, responseHandler);
                  System.out.println(responseBody);
            } catch (Exception e) {

  e.printStackTrace();

}
  }

  private static byte[] getBytes(String filepath) throws Exception{
                  File file = new File(filepath);
                  //init array with file length
                  byte[] bytesArray = new byte[(int) file.length()];

                  FileInputStream fis = new FileInputStream(file);
                  fis.read(bytesArray); //read file into bytes[]
                  fis.close();

                  return bytesArray;
          }

这可以正常工作,但是当我尝试上传一个csv文件时,它不起作用。

我用csv更改了文件,更改了url中的文件名,并将内容类型更改为“ text / csv”。

要使此功能生效,我应该更改什么?

1 个答案:

答案 0 :(得分:-1)

如果您要上传文件,则您的请求具有其他内容类型,因此您必须使用分段请求。参见What is http multipart request?