2015-05-27 127 views
1

我正在尝试使用Java执行CURL请求。卷曲的要求如下:使用HTTP的Java 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); 

代码编译并运行良好,但它没有返回任何内容。我哪里错了?

+0

看到这个问题: http://stackoverflow.com/questions/2793150/using-java- net-urlconnection-fire-and-handle-http-requests – inquizitive

+0

是否有您可以提供的临时用户名和密码?在任何时候都有例外吗? –

+0

没有例外抛出,我会尝试设置临时访问。 – Colin747

回答

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

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

--Here是代码---

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

--notice,我用这个代码来查看某个帐户上某个网站存在,因为它输出的一切,我要做的就是找到代码中的特定规则可以告诉我该用户是否存在。那么我真的不确定这是否可以帮助你,但它可能是。好运...