簡體   English   中英

java中的curl命令等效

[英]curl command equivalent in java

這是我的 curl 命令:

curl https://login.xyz.com/v1/oauth/token -H "Accept:
application/json" --data 'client_id=client_id' --data
'client_secret=client_secret' --data 'redirect_uri=redirect_uri'
--data 'code=code'

我正在嘗試將其發布在 Java 中。 這是我想要做的:

String resourceUrl = "https://login.xyz.com/v1/oauth/token?client_id=<client.id>&client_secret=<client.secret>&redirect_uri=https://login.xyz.com/user/login&code=<code>";
HttpURLConnection httpcon = (HttpURLConnection) ((new URL(resourceUrl).openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestMethod("POST");
httpcon.connect();      
System.out.println(httpcon.getHeaderField(0));

但我收到 HTTP/1.1 500 內部服務器錯誤

我沒有測試,只是通過查看文檔和源代碼,我可以看到 curl 命令和 Java 實現之間的一些差異:

卷曲:

  • 執行 POST
  • 內容類型是 application/x-www-form-urlencoded

卷曲手冊頁

-d, --data

(HTTP) 將 POST 請求中的指定數據發送到 HTTP 服務器,就像瀏覽器在用戶填寫 HTML 表單並按下提交按鈕時所做的那樣。 這將導致 curl 使用內容類型 application/x-www-form-urlencoded 將數據傳遞到服務器。 與 -F, --form 比較。

另請參閱: 如何在 HTTP POST 請求中發送參數?

Java實現:

  • 執行 POST 但 URL 與 GET 類似(您將請求方法設置為 POST 但您在 URL 查詢字符串中傳遞參數)
  • 內容類型是應用程序/json

我希望這有幫助。

public class CURLTest {
    public void main(String[] args) throws IOException {
        sendData();
    }

    public String sendData() throws IOException {
        // curl_init and url


        URL url = new URL( "Put the Request here");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        // CURLOPT_POST
        con.setRequestMethod("POST");

        // CURLOPT_FOLLOWLOCATION
        con.setInstanceFollowRedirects(true);

        String postData = "my_data_for_posting";
        con.setRequestProperty("Content-length",
            String.valueOf(postData.length()));

        con.setDoOutput(true);
        con.setDoInput(true);

        DataOutputStream output = new DataOutputStream(con.getOutputStream());
        output.writeBytes(postData);
        output.close();

        // "Post data send ... waiting for reply");
        int code = con.getResponseCode(); // 200 = HTTP_OK
        System.out.println("Response    (Code):" + code);
        System.out.println("Response (Message):" + con.getResponseMessage());

        // read the response
        DataInputStream input = new DataInputStream(con.getInputStream());
        int c;
        StringBuilder resultBuf = new StringBuilder();
        while ((c = input.read()) != -1) {
            resultBuf.append((char) c);
        }
        input.close();

        return resultBuf.toString();
    }
}

這是我將如何做的一個例子

暫無
暫無

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

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