0

这是我的第一个问题。我喜欢 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]

现在,我知道了基本的东西,而且我很确定我已经处理好了它们……比如设置标题 Accept application/json、Content-Type application/json 等。

任何建议将不胜感激。我是使用 HttpClient 的新手,我有点迷失了哈哈。多谢你们!

4

1 回答 1

0

The problem is that this server requires authentication and you're not providing it (or using invalid credentials). I can tell that because the response code was 401 (Unauthorized).

401: Similar to 403 Forbidden, but specifically for use when authentication is required and has failed or has not yet been provided [...]

HTTPClient's home page has a lot of information regarding authentication. You can check how to do that here also check some code examples here.

于 2013-06-27T20:29:05.683 回答