我试图提取一个网站的来源,我已经研究了一点,许多解决方案指向使用HTTPClient和HTTPContext,但问题是我不能使用URL来获取这个来源。我使用的网站是基于登录的,不管你是谁登录的,它都显示相同的URL(但是,当然,要提取的信息是不同的,基于用户)。因此,我想知道是否有一种方法可以直接从webview或类似的东西中获取源。总之,我不能使用URL中介,因为它是统一的,基本上重定向到一个通用的登录页面。
抱歉,如果我错过了什么;我是新手。提前感谢您的帮助。
编辑:
我发现了一个不同的URL,每个用户 是不同的,但有一个(另一个)相关的问题:使用jsoup,我可以执行jsoup .connect("http://www.stackoverflow.com/").get().html();(用我想要访问的URL代替),这确实得到了HTML源,但问题再次出现,当我试图访问一个用户/密码保护的网站时,它要求登录信息。我需要能够输入用户名和密码一次,并基本上将其存储在某种临时的东西(cookie/缓存?),并保留jsoup的信息,以停止查询登录凭据每次我请求基于某个URL的源。
如果我理解对了(如果我没理解对请告诉我):
如果用户/密码受保护,你应该发出一个Http Post(这是你从浏览器中做的)并从该Post中获得响应吗?像这样:
http://www.informit.com/guides/content.aspx?g=java& seqNum = 44
编辑:这里是一个示例
我有一个看起来像这样的页面(这是过度简化,但无论如何,它是):
<form action="../../j_spring_security_check" method="post" >
<input id="j_username" name="j_username" type="text" />
<input id="j_password" name="j_password" type="password"/>
<input type="image" class="submit" id="login" name="login" />
</form>
如果它是一个网页,你必须提供用户名/密码,以获得实际的内容"之后"这个登录页面。你真正发出的是一个HTTP POST(我打赌在你的情况下也是一样的)。
现在以编程的方式获得相同的功能…
您将需要apache http客户端库(您可能不需要它,但这是一种简单的方法)。下面是它的maven依赖。你打算在Android上这么做,对吗?apache http客户端是Android的默认设置。
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
public class HttpPost {
public static void main(String[] args) {
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod("http://localhost:20000/moika/moika/j_spring_security_check");
postMethod.addParameter("j_username", "ACTUAL_USER");
postMethod.addParameter("j_password", "ACTUAL_PASSWORD");
try {
int status = httpClient.executeMethod(postMethod);
System.out.println("STATUS-->" + status);
if(status == 302){
Header header = postMethod.getResponseHeader("location");
String location = header.getValue();
System.out.println("HEADER_VALUE-->" + location);
GetMethod getMethod = new GetMethod(location);
httpClient.executeMethod(getMethod);
String content = getMethod.getResponseBodyAsString();
System.out.println("CONTENT-->" + content);
}
String contentInCaseOfNoRedirect = postMethod.getResponseBodyAsString();
} catch (Exception exception){
exception.printStackTrace();
}
}
}
这可能看起来有点奇怪,但我执行重定向(302),在RCF中似乎有一个问题,因此有一个小的解决方案。
如果你没有在服务器端执行任何重定向,那么你可以忽略我检查302的部分。
看看什么适合你。
欢呼,尤金。
参见http://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html
或查看示例代码
如何读取URL
try{
URL oracle = new URL("http://www.w3schools.com/html/html_tables.asp");
URLConnection yc = oracle.openConnection();
InputStream is = yc.getInputStream();
String inputLine;
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}catch(Exception ex){
ex.printStackTrace();
}