簡體   English   中英

使用HTTP的Java CURL請求

[英]Java CURL request using HTTP

我正在嘗試使用Java執行CURL請求。 CURL請求如下:

curl https://apis.sen.se/v2/feeds/N4hSBSpFlYzXT6ZN2IA1KadgSR9rTazv/events/?limit=1 -u username:password

我正在嘗試執行以下請求:

String stringUrl = "https://apis.sen.se/v2/feeds/N4hSBSpFlYzXT6ZN2IA1KadgSR9rTazv/events/?limit=1";
URL url = new URL(stringUrl);
URLConnection uc = url.openConnection();

uc.setRequestProperty("X-Requested-With", "Curl");

String userpass = "username" + ":" + "password";
String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
uc.setRequestProperty("Authorization", basicAuth);

InputStreamReader inputStreamReader = new InputStreamReader(uc.getInputStream());

並且我試圖查看inputStreamReader的內容,如下所示:

int data = inputStreamReader.read();
char aChar = (char) data;
System.out.println(aChar);

代碼正在編譯並且可以正常運行,但是什么也不返回。 我要去哪里錯了?

我最終使用以下代碼使其工作:

public static void main(String args[]) throws IOException {
        String stringUrl = "url";
        URL url = new URL(stringUrl);
        URLConnection uc = url.openConnection();
        uc.setRequestProperty("X-Requested-With", "Curl");
        String userpass = "username" + ":" + "password";
        String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
        uc.setRequestProperty("Authorization", basicAuth);
        StringBuilder html = new StringBuilder();
        BufferedReader input = null;
        try {
          input = new BufferedReader(new InputStreamReader(uc.getInputStream()));
          String htmlLine;
          while ((htmlLine = input.readLine()) != null) {
            html.append(htmlLine);
          }
        }
        catch (IOException e) {
          e.printStackTrace();
        }
        finally {
          try {
            input.close();
          }
          catch (IOException e) {
            e.printStackTrace();
          }
        }
        System.out.println(html.toString());
    }

我也在嘗試做那件事。 我有某種解決方法,但它會讀取所看到的所有內容。

-這是代碼-

        String params = "some-parameters";
        URL url = new URL("some-website");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("POST");
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(params);
        wr.flush();
        wr.close();
        con.getResponseCode();

        BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String line;
        StringBuffer buffer = new StringBuffer();

        while((line = reader.readLine()) != null) {
            buffer.append(line+"\n");
        }
        reader.close();

        System.out.print(buffer.toString());

-注意,我使用此代碼來查看某個帳戶是否存在於某個網站上,因為它會輸出所有內容,所以我要做的是在代碼上找到特定的規律性,該規則可以告訴我該用戶是否存在。 好吧,我什至不確定這是否能幫到您,但可能會。 祝好運...

暫無
暫無

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

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