簡體   English   中英

如何將httpput寫入Java

[英]How to write httpput to java

我想將Curl寫入Java:

curl -X PUT -u username:password http://localhost:80/api/client/include/clientID

那就是我用谷歌搜索的內容,但是我的問題是我如何傳遞client_id和client的值,因為它們之間有一個/ include。 我對如何寫卷發有點困惑。 誰能幫我?

public String RestPutClient(String url, int newValue, int newValue2) {
            // example url : http://localhost:80/api/
            DefaultHttpClient httpClient = new DefaultHttpClient();
            StringBuilder result = new StringBuilder();
            try {
                HttpPut putRequest = new HttpPut(url);
                putRequest.addHeader("Content-Type", "application/json");
                putRequest.addHeader("Accept", "application/json");
                JSONObject keyArg = new JSONObject();
                keyArg.put("value1", newValue);
                keyArg.put("value2", newValue2);
                StringEntity input;
                try {
                    input = new StringEntity(keyArg.toString());
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    return success;
                }
                putRequest.setEntity(input);
                HttpResponse response = httpClient.execute(putRequest);
                if (response.getStatusLine().getStatusCode() != 200) {
                    throw new RuntimeException("Failed : HTTP error code : "
                            + response.getStatusLine().getStatusCode());
                }
                BufferedReader br = new BufferedReader(new InputStreamReader(
                        (response.getEntity().getContent())));
                String output;
                while ((output = br.readLine()) != null) {
                    result.append(output);
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result.toString();
        }

我假設您傳遞的參數應該代表client和clientID。 您只需要構建從參數傳遞到HttpPut的URL。

如果這些是您的參數

url = "http://localhost:80/api/";
newValue = "client";
newValue2 = "clientID";

然后您的HttpPut初始化看起來像這樣

HttpPut putRequest = new HttpPut(url + newValue + "/include/" + newValue2);

另請參閱: 如何在Java中連接兩個字符串?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM