这是我的第一个问题。我喜欢stackOverflow,但我一直是读者,而不是作家。现在这里什么都没有:
所以我看到了很多不同的问题,相信我,我看了......但是他们似乎都没有完全回答我的问题。我正在设计一个测试工具来测试API,它涉及使用HttpClient(在Java中)发送HTTP请求。对于某些请求,例如POST请求,必须随请求一起发送JSON字符串或XML字符串。 (我只是在这里询问JSON,如果有人也知道如何处理XML,我会喜欢它,但我会将它保存为另一个问题。)
无论如何,到目前为止,我有以下代码,看起来它应该做我想要的...但我得到400错误。我将假设我已经正确创建了HttpClient和HttpPost的实例,应用了适当的标题等等......相关部分如下:
JSONObject JSONpayload = new JSONObject();
JSONpayload.put("quantity", 1);
JSONpayload.put("sku", "21-53429");
String JSONstring = JSONpayload.toString();
System.out.println("JSON PAYLOAD BEING SENT: " + JSONstring);
request.setEntity(new StringEntity(JSONstring));
response = client.execute(request);
System.out.println("SERVER RESPONSE STRING: " + response.toString());
我收到以下输出:
JSON PAYLOAD BEING SENT: {"quantity":1,"sku":"21-53429"}
SERVER RESPONSE STRING: HTTP/1.1 401 Unauthorized
[Date: Thu, 27 Jun 2013 19:57:29 GMT,
Server: Mule Core/3.3.1,
Set-Cookie: sid=h8jumUyMxMztmB1AHtbvmUzzc9WchbiR9dQahD6Q; Version=1;
Domain=192.168.235.9;
Path=/,
http.status: 401,
X-MULE_SESSION: rO0ABXNyACNvcmcubXVsZS5zZXNzaW9uLkRlZmF1bHRNdWxlU2Vzc2lvbi7rdtEW7GGKAwAEWgAFdmFsaWRMAA1mbG93Q29uc3RydWN0dAAmTG9yZy9tdWxlL2FwaS9jb25zdHJ1Y3QvRmxvd0NvbnN0cnVjdDtMAAJpZHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wAD3NlY3VyaXR5Q29udGV4dHQAJ0xvcmcvbXVsZS9hcGkvc2VjdXJpdHkvU2VjdXJpdHlDb250ZXh0O3hwAXB0ACRjYzQwMmMwNy1kZjYzLTExZTItOGY1Yi1kOTk2MTM2MzZkZjJwc3IAJWphdmEudXRpbC5Db2xsZWN0aW9ucyRTeW5jaHJvbml6ZWRNYXAbc/kJS0s5ewMAAkwAAW10AA9MamF2YS91dGlsL01hcDtMAAVtdXRleHQAEkxqYXZhL2xhbmcvT2JqZWN0O3hwc3IAJG9yZy5tdWxlLnV0aWwuQ2FzZUluc2Vuc2l0aXZlSGFzaE1hcJ3R2e9nRc4AAwAAeHB3DD9AAAAAAAAQAAAAB3QABWR1bW15dAAYOU9WX0FBQUJHQmdBQUFFX0lTQVFBNGMydAAJUm91dGVkVVJMdABhaHR0cDovLzE5Mi4xNjguMjM1Ljk6MzA4MC9nc2kvcmVzdC9XRlMvVE1TTkEtVE1TVVMtU2l0ZS9yZXN0L2NhcnRzLzlPVl9BQUFCR0JnQUFBRV9JU0FRQTRjMi9pdGVtc3QAC0NvbnRleHRQYXRodAATZ3NpLWV3cy1zZXJ2aWNlL3N2Y3QAC291dHB1dC10eXBldAAQYXBwbGljYXRpb24vanNvbnQAClJlcXVlc3RVUkx0AEsvZ3NpLWV3cy1zZXJ2aWNlL3N2Yy92MS4wL3N0b3Jlcy9UTVNVUy9jYXJ0cy85T1ZfQUFBQkdCZ0FBQUVfSVNBUUE0YzIvaXRlbXN0AAdTdG9yZUlEdAAMc3RvcmVzL1RNU1VTdAAKaW5wdXQtdHlwZXEAfgATeHEAfgAJeHg=,
X-MULE_ENCODING: UTF-8,
Content-Type: text/plain,
Transfer-Encoding: chunked]
现在,我知道基本的东西,我很确定我已经处理好了......比如设置标题接受application / json,Content-Type application / json等。
任何建议都将不胜感激。我是新手使用HttpClient,我有点迷失哈哈。谢谢你们!