使用HTTP的Java CURL请求

时间:2015-05-27 14:03:12

标签: java curl

我正在尝试使用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);

代码正在编译并正常运行,但它什么也没有返回。我哪里错了?

2 个答案:

答案 0 :(得分:1)

我最终使用以下代码开始工作:

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());
    }

答案 1 :(得分:0)

我也试图做那件事。我有一些解决方法,但它会读取它看到的所有内容。

- 这是代码---

        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());

- 请注意,我使用此代码查看某个网站上是否存在某个帐户,因为它输出了所有内容,我所做的是在代码上找到一个特定的规则,可以告诉我该用户是否存在。嗯,我甚至不确定这是否可以帮助你,但它可能会。祝你好运......