我正在尝试向node.js服务器发帖子但是由于某种原因,无论我尝试什么,身体对我来说总是空的。 我现在正在测试requestb.in,它也总是空着。
这是我用于发布的代码:
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 raw body应该包含json字符串,对吧?
有什么建议吗?
答案 0 :(得分:1)
使用HttpUrlConnection
时可能会犯很多错误。我承认我没有看到任何错误,但这并不意味着什么。
由于Google不建议使用HttpClient和AndroidHttpClient(FROYO或更早版本除外),而是使用we should use HttpUrlConnection,因此您采用正确的方式(从Android角度来看)。
当为名为DavidWebb的HttpUrlConnection使用非常轻量级的包装器时,代码看起来像这样(我省略了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
确实接受了它:
json = "{'string':'string'}";
但这不是有效的JSON(这里在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;博士强>
HttpUrlConnection
或使用简单的抽象库对于讨厌的错误,您可以调试node.js代码(或console.log(req)
)或使用Wireshark之类的工具。
答案 1 :(得分:0)
尝试使用此代码发送字符串....在HttpPost中,您应该使用键值对来发送数据。
HttpPost httppost = new HttpPost(SERVER_URL);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("REQUEST", req));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = httpclient.execute(httppost);
答案 2 :(得分:0)
我无法让HttpPost工作,但是HttpUrlConnection可以工作。它解决了我的问题,但没有解决httpPost的神秘无身体问题。
这是我的解决方案:
public static String post(String ur2l, String json) {
StringBuilder stringBuffer = new StringBuilder();
BufferedReader bufferedReader = null;
try {
URL url = new URL(ur2l);
HttpURLConnection conn;
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-type", "application/json");
conn.setRequestProperty("hmac", Methods.getMethods().getHmac(json));
conn.setDoOutput(true);
OutputStream os = null;
try {
os = conn.getOutputStream();
os.write(json.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
os.close();
conn.connect();
int respCode = conn.getResponseCode();
if (respCode == 200) {
InputStream inputStream = conn.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String readLine = bufferedReader.readLine();
while (readLine != null) {
stringBuffer.append(readLine);
stringBuffer.append("\n");
readLine = bufferedReader.readLine();
}
}
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return stringBuffer.toString();
}
答案 3 :(得分:0)
我不确定这是问题所在。你能试一试吗?
您正在发送无效的JSON格式字符串。这使得服务器无法接受您的无效json字符串,因此您的正文为空。要解决此问题,请更改以下代码。
StringEntity se = new StringEntity("{\"string\":\"string\"}", HTTP.UTF_8);