我可以使用CURL -u访问XML数据,并使用HTTP Basic Auth在浏览器中获取它。如何在Java中复制该过程?

时间:2013-08-19 05:26:44

标签: java xml http authentication recurly

curl -u APIKEY https://api.recurly.com/v2/accounts

在终端...... 像魅力一样工作并获得我想要的XML ......

更新

https://companyName.recurly.com/v2/accounts.xml 要求输入用户名和密码以从浏览器窗口访问xml。我可以输入,浏览器将为我显示xml数据。 我只需要一个准确的内容来查看将xml doc放入我的“System.out.println()”屏幕的内容。我会从那里弄明白,我只需要在屏幕上获取数据!

3 个答案:

答案 0 :(得分:1)

你可以在你的java代码中使用HttpClient

参见链接

http://hc.apache.org/httpclient-3.x/

答案 1 :(得分:1)

我会使用HttpURLConnection来获取它

    URL url = new URL(fileURL);
    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();

    System.out.println("Content-Type = " + httpConn.getContentType());
    System.out.println("Content-Disposition = " + httpConn.getHeaderField("Content-Disposition"));
    System.out.println("Content-Length = " + httpConn.getContentLength());

   InputStream inputStream = httpConn.getInputStream();

答案 2 :(得分:0)

这是我正在寻找的答案。我在这个网站找到了...... http://www.avajava.com/tutorials/lessons/how-do-i-connect-to-a-url-using-basic-authentication.html。我很兴奋,我终于开始工作了。这就像魅力只是用你的信息取代“companyName”和“APIKEY”。 感谢大家和他们的意见和帮助!

package getrecurly;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.codec.binary.Base64;

/**
 *
 * @author jackcrishjr
 */
public class GetRecurly{


public static void main(String[] args) {

        try {
            String webPage = "https://companyName.recurly.com/v2/accounts.xml";
            String name = "APIKEY";
            String password = "APIKEY";

            String authString = name + ":" + password;
            System.out.println("auth string: " + authString);
            byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
            String authStringEnc = new String(authEncBytes);
            System.out.println("Base64 encoded auth string: " + authStringEnc);

            URL url = new URL(webPage);
            URLConnection urlConnection = url.openConnection();
            urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
            InputStream is = urlConnection.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);

            int numCharsRead;
            char[] charArray = new char[1024];
            StringBuffer sb = new StringBuffer();
            while ((numCharsRead = isr.read(charArray)) > 0) {
                sb.append(charArray, 0, numCharsRead);
            }
            String result = sb.toString();

            System.out.println("*** BEGIN ***");
            System.out.println(result);
            System.out.println("*** END ***");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}