httpPost setEntity总是空 [英] httpPost setEntity always empty

查看:1581
本文介绍了httpPost setEntity总是空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一个张贴到的node.js服务器,但由于某种原因,身体总是空的,我不管我试试。
现在我对测试和requestb.in它总是空的也有。

I'm trying to make a post to a node.js server but for some reason the body is always empty for me no matter what I try. I'm testing now towards requestb.in and its always empty there too.

这是code我用发帖:

This is the code I use for posting:

public static String post(String url, String json) {
    StringBuilder stringBuffer = new StringBuilder();
    BufferedReader bufferedReader = null;
    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpPost httpPost = new HttpPost("http://requestb.in/14a9s7m1");
        StringEntity se = new StringEntity("{'string':'string'}", HTTP.UTF_8);
        se.setContentType("application/json; charset=UTF-8");
        httpPost.setEntity(se);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("hmac", Methods.getMethods().getHmac(json));

        HttpResponse httpResponse = httpClient.execute(httpPost, localContext);
        InputStream inputStream = httpResponse.getEntity().getContent();
        bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        String readLine = bufferedReader.readLine();
        while (readLine != null) {
            stringBuffer.append(readLine);
            stringBuffer.append("\n");
            readLine = bufferedReader.readLine();
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return stringBuffer.toString();
}

这是requestb.in http://requestb.in/14a9s7m1?inspect
原体应该包含JSON字符串,对吧?

This is the requestb.in http://requestb.in/14a9s7m1?inspect raw body should contain the json string, right?

有什么建议?

推荐答案

您可以使用时犯下许多错误 HttpURLConnection类。我承认,我没有看到任何错误,但是这并不意味着什么。

You can make many mistakes when using HttpUrlConnection. I admit that I don't see any error, but this doesn't mean anything.

由于谷歌不推荐使用的HttpClient和AndroidHttpClient(除了升级Froyo或以上),但的我们应该使用HttpURLConnection的相反,你以正确的方式(从Android的角度)。

Since Google doesn't recommend using HttpClient and AndroidHttpClient (except for FROYO or older), but we should use HttpUrlConnection instead, you're on the right way (from a Android perspective).

当使用HttpURLConnection类称为 DavidWebb 中,code看起来像这样(一个非常轻量级的包装我离开了HMAC-代):

When using a very lightweight wrapper for HttpUrlConnection called DavidWebb, the code looks like this (I left out hmac-generation):

public class TestWebbRequestBin {

    @Test public void stackOverflow20543115() throws Exception {
        Webb webb = Webb.create();
        webb.setBaseUri("http://requestb.in");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("string", "string");
        String json = jsonObject.toString(); // {"string":"string"}

        Response<String> response = webb
                .post("/1g7afwn1")
                .header("Accept", "application/json")
                .header("Content-type", "application/json")
                .header("hmac", "some-hmac-just-a-test")
                .body(json)
                .asString();

        assertEquals(200, response.getStatusCode());
        assertTrue(response.isSuccess());

        String body = response.getBody();
        assertEquals("ok\n", body);
    }

}

当我张贴JSON看起来像你的榜样, requestb.in 并接受它:

When the JSON I post looks like in your example, requestb.in does accept it:

    json = "{'string':'string'}";

但是,这不是有效的JSON(node.js的在这里测试过):

But this is not valid JSON (here tested in node.js):

> JSON.parse("{'string':'string'}")
    SyntaxError: Unexpected token '
    at Object.parse (native)
    at repl:1:7
    at REPLServer.self.eval (repl.js:110:21)
    at Interface.<anonymous> (repl.js:239:12)

TL;博士


  • 小心发送有效的JSON

  • HttpURLConnection类或使用一个简单的抽象库

  • Take care to send valid JSON
  • Master HttpUrlConnection or use a simple abstraction library

有关讨厌的错误,你既可以调试的Node.js code(或的console.log(REQ))或使用类似的 Wireshark的

For nasty bugs you could either debug your node.js code (or console.log(req)) or use a tool like Wireshark.

这篇关于httpPost setEntity总是空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆