【发布时间】:2014-07-18 15:50:31
【问题描述】:
所以我对 Java 和特别是 android 编程还很陌生。我正在尝试创建一个从金融网站提取数据的应用程序(如果它更容易的话,可能带有 API)。
我尝试的第一步是从网站上提取任何文本。我目前正在使用 .txt URL 进行练习,这是我目前的代码:
package com.example.datatesting;
import java.io.IOException;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.util.ByteArrayBuffer;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(R.id.textView1);
String myString = null;
try{
URL myURL = new URL("http://www.something.com/readme.txt");
URLConnection connect= myURL.openConnection();
InputStream ins = connect.getInputStream();
BufferedInputStream buff = new BufferedInputStream(ins);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while( (current=buff.read()) !=-1){
baf.append( (byte) current);
}
myString = new String(baf.toByteArray());
tv.setText("hello1");
}
catch(Exception e){
myString = e.getMessage();
tv.setText("hello2");
}
}
}
代码打印“hello2”。我不太确定出了什么问题或如何解决问题,因此 try 块可以正常工作。
我也在清单中添加了这个:
<uses-permission
android:name="android.permission.INTERNET" />
我没有收到应用程序允许互联网访问的提示,是自动的吗?
感谢您的帮助和指导。
************编辑更新:我添加了 cmets 以指示混乱的区域
public class MainActivity extends Activity {
private TextView tv;
private String myString = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView1);
//I'm not sure what to put into execute(...) so I added this here, but this requires
//a try catch block which would go back to my original issue...
URL myURL = new URL("http://www.anddev.org/images/tut/basic/getdatafromtheweb/loadme.txt");
new DataExtract().execute(myURL);
}
private class DataExtract extends AsyncTask<URL, Void, Void>{
protected Void doInBackground(URL...urls){ //this needs a return type but I'm not returning anything
try{
URL myURL = new URL("http://www.anddev.org/images/tut/basic/getdatafromtheweb/loadme.txt");
URLConnection ucon = myURL.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while( (current=bis.read()) !=-1){
baf.append( (byte) current);
}
myString = new String(baf.toByteArray());
tv.setText("hello1");
}
catch(Exception e){
myString = e.getMessage();
tv.setText("hello2");
}
}
protected void onPostExecute(Void result){ //is this an acceptable param?
tv.setText(myString);
}
}
}
【问题讨论】:
标签: java android web-scraping data-mining