首页 > 解决方案 > 如何使用 Apache HttpClient 发布非 JSON 请求?

问题描述

我要打一个API,它将返回字符串数据,并且我想发送字符串类型的数据(段落中的文本文件)。

标签: javajsonhttpclientapache-httpclient-4.x

解决方案


您可以使用带有 http实体的 Apache httpcomponents

以下是在 POST 请求中发送文件的示例:

File file = new File("somefile.txt");
FileEntity entity = new FileEntity(file, ContentType.create("text/plain", "UTF-8"));        

HttpPost httppost = new HttpPost("http://localhost/action.do");
httppost.setEntity(entity);

如果你想要一个文本内容,你可以使用StringEntity

StringEntity myEntity = new StringEntity("something", ContentType.create("text/plain", "UTF-8"));

推荐阅读