使用Apache HttpClient将命令转换为Java代码

时间:2013-04-12 18:24:52

标签: curl apache-httpclient-4.x put

我正在尝试将java客户端编写为restful service。身份验证没有问题,但我不知道如何添加--data参数。

这是curl命令:

curl -i -L --user user:password -X PUT -H "Content-Type: application/json" 
--data '{"translation": {"0": "zero"}}' 
http://www.transifex.com/api/2/project/p1/resource/testspot/translation/ar/string/fbb05a9f1ad844fcd1740ce9bf8f2574/

如何为该curl语句编写java客户端。我尝试了多种解决方案建议,但没有帮助。

这是我的java代码:

public static JsonElement httpPut(String username, String password, String url, String putText) throws UnauthorizedAccessException, Exception {

    JsonElement jelement = null;
    try {

        String basicAuth = Base64.encodeBase64String(("gccster" + ":" + "test").getBytes());
        HttpClient client = new DefaultHttpClient();
        HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);

        HttpPut httpPut = new HttpPut("https://www.transifex.com/api/2/project/demoproject1/resource/test/translation/el/string/bff3b5b0513a5e4821f649ffcca93069/");
        httpPut.setHeader("Authorization", "Basic " + basicAuth);
        httpPut.addHeader("Accept", "application/json");
        httpPut.addHeader("Content-Type", "application/json");

        //StringEntity putEntity = new StringEntity(putText, "UTF-8");
        //putEntity.setContentType("application/json");
        //httpPut.setEntity(putEntity);
        HttpResponse transifexResponse = client.execute(httpPut);

        StatusLine statusLine = transifexResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        //if (statusCode == 200) {
        HttpEntity entity = transifexResponse.getEntity();
        InputStream content = entity.getContent();

        String responseText = readInputStream(content);

        if (responseText.equals("Authorization Required")) {
            throw new UnauthorizedAccessException("Anauthorized Exception");
        } else {
            jelement = new JsonParser().parse(responseText.toString());
        }
        //}
    } catch (UnauthorizedAccessException ex) {
        throw ex;
    } catch (Exception ex) {
        throw ex;
    }

    return jelement;

}

0 个答案:

没有答案