简单的问题,如何获取http://www.minecraft.net/haspaid.jsp?user=somethinghere的内容?我将在文本文件中有一个用户名列表,我想查看所有用户名,看看他们是否付款。此网页的内容将为true或false。没有HTML,只有“真实”或“虚假”。我如何获得该内容?我不需要任何花哨的东西。这是我第一次用Java处理基于Web的东西。
答案 0 :(得分: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
}
答案 1 :(得分:1)
HttpClient或春天RestTemplate可以胜任。
春天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);
}
}