【问题标题】:Java: Adding raw data to payload Httpost requestJava:将原始数据添加到有效负载 Httpost 请求
【发布时间】:2013-11-20 10:58:49
【问题描述】:

我打算在 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);

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

有什么帮助吗?

【问题讨论】:

标签: java http-post payload


【解决方案1】:

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

Commons HttpClient(旧 - 生命终结)

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

httpPost.setRequestEntity(new StringRequestEntity(stringData));

用于二进制数据的RequestEntity 的实现是ByteArrayRequestEntity 用于byte[]FileRequestEntity 从文件中读取数据(自3.1 起)和InputStreamRequestEntity,它可以从任何输入流中读取。

3.0之前可以直接设置String或者InputStream,例如ByteArrayInputStream,作为请求正文:

httpPost.setRequestBody(stringData);

httpPost.setRequestBody(new ByteArrayInputStream(byteArray));

现在不推荐使用此方法。

HTTP 组件(新)

如果使用较新的HTTP components API,方法、类和接口名称略有变化,但概念是一样的:

httpPost.setEntity(new StringEntity(stringData));

其他Entity 实现:ByteArrayEntityInputStreamEntityFileEntity、...

【讨论】:

    【解决方案2】:

    我犯了一个常见的错误 json 对象的序列是错误的。例如,我像 first_name,email..etc 一样发送它。正确的顺序是 email,first_name

    我的代码

    boolean result = false;
        HttpClient hc = new DefaultHttpClient();
        String message;
    
    HttpPost p = new HttpPost(url);
    JSONObject object = new JSONObject();
    try {
    
        object.put("updates", updates);
        object.put("mobile", mobile);
        object.put("last_name", lastname);
        object.put("first_name", firstname);
        object.put("email", email);
    
    } catch (Exception ex) {
    
    }
    
    try {
    message = object.toString();
    
    
    p.setEntity(new StringEntity(message, "UTF8"));
    p.setHeader("Content-type", "application/json");
        HttpResponse resp = hc.execute(p);
        if (resp != null) {
            if (resp.getStatusLine().getStatusCode() == 204)
                result = true;
        }
    
        Log.d("Status line", "" + resp.getStatusLine().getStatusCode());
    } catch (Exception e) {
        e.printStackTrace();
    
    }
    
    return result;
    

    Answer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-09
      • 2017-12-17
      • 2017-02-22
      • 2018-12-27
      • 2013-03-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多