Android의 HTML 링크에서 페이지의 HTML 소스를 얻는 방법은 무엇입니까?
-
19-09-2019 - |
문제
나는 링크에서 웹 페이지 소스를 가져 와서 해당 페이지에서 HTML을 구문 분석 해야하는 응용 프로그램을 작성하고 있습니다.
나에게 몇 가지 예를 들어, 그러한 앱 작성을 시작해야 할 곳을 시작할 수 있습니까?
해결책
당신이 사용할 수있는 httpclient HTTP를 수행하려면 다음과 같은 HTML 응답을 검색하고 검색합니다.
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
String html = "";
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
str.append(line);
}
in.close();
html = str.toString();
다른 팁
이 질문은 조금 오래되었지만 지금 내 대답을 게시해야한다고 생각했습니다. DefaultHttpClient
, HttpGet
, 등이 더 이상 사용되지 않습니다. 이 기능은 URL이 주어지면 HTML을 가져 와서 반환해야합니다.
public static String getHtml(String url) throws IOException {
// Build and set timeout values for the request.
URLConnection connection = (new URL(url)).openConnection();
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.connect();
// Read and store the result line by line then return the entire string.
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder html = new StringBuilder();
for (String line; (line = reader.readLine()) != null; ) {
html.append(line);
}
in.close();
return html.toString();
}
public class RetrieveSiteData extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
StringBuilder builder = new StringBuilder(100000);
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
builder.append(s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return builder.toString();
}
@Override
protected void onPostExecute(String result) {
}
}
그것을 좋아합니다
new RetrieveFeedTask(new OnTaskFinished()
{
@Override
public void onFeedRetrieved(String feeds)
{
//do whatever you want to do with the feeds
}
}).execute("http://enterurlhere.com");
검색 피드 타스크. 클래스
class RetrieveFeedTask extends AsyncTask<String, Void, String>
{
String HTML_response= "";
OnTaskFinished onOurTaskFinished;
public RetrieveFeedTask(OnTaskFinished onTaskFinished)
{
onOurTaskFinished = onTaskFinished;
}
@Override
protected void onPreExecute()
{
super.onPreExecute();
}
@Override
protected String doInBackground(String... urls)
{
try
{
URL url = new URL(urls[0]); // enter your url here which to download
URLConnection conn = url.openConnection();
// open the stream and put it into BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = br.readLine()) != null)
{
// System.out.println(inputLine);
HTML_response += inputLine;
}
br.close();
System.out.println("Done");
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return HTML_response;
}
@Override
protected void onPostExecute(String feed)
{
onOurTaskFinished.onFeedRetrieved(feed);
}
}
Ontaskfinished.java
public interface OnTaskFinished
{
public void onFeedRetrieved(String feeds);
}
다른 하나 중 하나 그래서 사후 답변이 도움이되었습니다. 이것은 줄별로 읽지 않습니다. HTML 파일에는 줄이 있다고 생각합니다 없는 사이. 전제 조건으로 프로젝트 설정에서 이러한 종속성을 추가하십시오 "com.koushikdutta.ion : 이온 : 2.2.1" 이 코드를 구현하십시오 Asynctask. 반품을 원한다면 -무엇- UI 스레드에 있으려면 상호 인터페이스로 전달하십시오.
Ion.with(getApplicationContext()). load("https://google.com/hashbrowns") .asString() .setCallback(new FutureCallback<String>() { @Override public void onCompleted(Exception e, String result) { //int s = result.lastIndexOf("user_id")+9; // String st = result.substring(s,s+5); // Log.e("USERID",st); //something } });
제휴하지 않습니다 StackOverflow