1

简单的问题,我如何获得http://www.minecraft.net/haspaid.jsp?user=somethinghere的内容?我将有一个文本文件中的用户名列表,我想浏览所有这些用户名,看看他们是否已经付款。这个网页的内容要么是真的,要么是假的。没有html,只有“真”或“假”。我如何获得该内容?我不需要任何花哨的东西。这是我第一次用 Java 处理基于 Web 的东西。

4

2 回答 2

2

您实际上是在询问如何使用 java API 执行 HTTP GET。这是代码片段。

URL url = new URL("http://www.minecraft.net/haspaid.jsp?user=somethinghere");
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
   // parse your content here
}
于 2011-11-20T09:12:27.470 回答
1

HttpClient或 spring RestTemplate可以完成这项工作。

与 spring 类似的东西RestTemplate

public class Foo {
    /** 
     * Production HTTP end point.
     */ 
    private static final String BASE_URL = "http://www.minecraft.net/haspaid.jsp";

    /**
     * {@link RestTemplate} for HTTP access.
     */
    @Autowire
    private RestTemplate restTemplate;

    /**
     * Constructor.
     */
    public Foo() {
        this.baseUrl = BASE_URL;
    }

    /**
     * Constructor for testing purposes.
     *
     * @param baseUrl HTTP end-point url to use.
     * @param restTemplate {@link RestTemplate} to use (a mock probably).
     */
    protected Foo(final String baseUrl, final RestTemplate restTemplate) {
        this.baseUrl = baseUrl;
        this.restTemplate = restTemplate;
    }

    /**
     * Check if user has paid.
     *
     * @param userName Name of the user to check.
     * @return true if user has paid
     */
    public boolean hasPaid(final String userName) {
        if (userName == null) {
            return false;
        }

        final String result = restTemplate.getForObject(this.baseUrl + 
            "?user={user}", String.class, userName);

        return Boolean.valueOf(result);
    }
}
于 2011-11-20T09:10:29.767 回答