我打算发送一个简单的 http post 请求,在有效负载中包含一个大字符串。
到目前为止,我有以下内容。
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("address location");
String cred = "un:pw";
byte[] authEncBytes = Base64.encodeBase64(cred.getBytes());
String authStringEnc = new String(authEncBytes);
httppost.setHeader("Authorization","Basic " + authStringEnc);
但是,我不知道如何将简单的 RAW 字符串附加到负载中。我能找到的唯一示例是实体中的名称值对,但这不是我想要的。
有什么帮助吗?
最佳答案
这取决于您使用的具体 HTTP-API:
Commons HttpClient(旧 - 生命终结)
从 HttpClient 3.0 开始,您可以为您的 PostMethod
指定一个 RequestEntity
:
httpPost.setRequestEntity(new StringRequestEntity(stringData));
RequestEntity
对二进制数据的实现是 ByteArrayRequestEntity
for byte[]
,FileRequestEntity
从中读取数据一个文件(自 3.1 起)和 InputStreamRequestEntity
,它可以从任何输入流中读取。
在 3.0 之前,您可以直接设置一个 String
或一个 InputStream
,例如一个 ByteArrayInputStream
,作为请求体:
httpPost.setRequestBody(stringData);
或
httpPost.setRequestBody(new ByteArrayInputStream(byteArray));
此方法现已弃用。
HTTP 组件(新)
如果您使用较新的 HTTP components API、方法、类和接口(interface)名称稍有变化,但概念是一样的:
httpPost.setEntity(new StringEntity(stringData));
其他 Entity
实现:ByteArrayEntity
、InputStreamEntity
、FileEntity
、...
关于Java:将原始数据添加到负载 Http Post 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20094042/