使用apache http客户端执行curl命令

时间:2014-12-05 07:13:11

标签: java json curl

我正在执行一个curl命令

curl -X POST -v -k --user admin:pass123 --data" {SOME JSON DATA}" --header" Content-Type:application / json" https://testhost.com:443/test/endpoint

这种成功与卷曲。

但是当我尝试用java代码执行它时,它失败了,因为给出了

此资源的身份验证失败。","代码":" 401"

这是我的java代码

    String content = "SOME JSON DATA";
    String user = "admin:pass123";
    String endpoint = "https://testhost.com:443/test/endpoint"; 

    DefaultHttpClient client = new DefaultHttpClient();

    HttpPost postRequest = new HttpPost(endpoint);
    postRequest.setHeader("Accept", "application/json");

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("user", user));
    nameValuePairs.add(new BasicNameValuePair("data", content));

    try {
        postRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));
       // postRequest.setEntity(new StringEntity(content));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    try {
        HttpResponse response = client.execute(postRequest);
        System.out.println(response.getStatusLine().getStatusCode());
        BufferedReader rd = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        System.out.println(result);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

有人可以解释我这是错误的原因吗?

0 个答案:

没有答案