Java:将原始数据添加到有效负载Httpost请求中

Jam*_*ren 5 java http-post payload

我打算在Payload中发送一个带有大字符串的简单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);
Run Code Online (Sandbox Code Playgroud)

但是,我不知道如何将简单的RAW字符串附加到有效负载中.我能找到的唯一例子是实体中的名称值对,但这不是我想要的.

任何帮助?

isn*_*bad 9

这取决于您使用的具体HTTP-API:

Commons HttpClient(旧的 - 生命的尽头)

从HttpClient 3.0开始,您可以RequestEntity为您指定PostMethod:

httpPost.setRequestEntity(new StringRequestEntity(stringData));
Run Code Online (Sandbox Code Playgroud)

的实施方式中RequestEntity的二进制数据是ByteArrayRequestEntitybyte[],FileRequestEntity其从文件读取的数据(自3.1)和InputStreamRequestEntity,它可以从任何输入流中读取.

在3.0之前,您可以直接设置一个String或一个InputStream,例如一个ByteArrayInputStream,作为请求主体:

httpPost.setRequestBody(stringData);
Run Code Online (Sandbox Code Playgroud)

要么

httpPost.setRequestBody(new ByteArrayInputStream(byteArray));
Run Code Online (Sandbox Code Playgroud)

此方法现已弃用.

HTTP组件(新)

如果您使用较新的HTTP组件 API,方法,类和接口名称会发生​​一些变化,但概念是相同的:

httpPost.setEntity(new StringEntity(stringData));
Run Code Online (Sandbox Code Playgroud)

其他Entity实现方式:ByteArrayEntity,InputStreamEntity,FileEntity,...