import android.os.Handler;
import android.os.Looper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class http_load_web_string {
public interface ActionListener{
public void get_string(String str);
}
public ActionListener actionListener=null;
private String target_url;
private String result;
private void load_json_from_url(String myurl){
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(myurl);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
result=buffer.toString();
}catch (Exception e){
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void load_from_url(String url){
this.target_url=url;
ExecutorService executor = Executors.newSingleThreadExecutor();
Handler handler = new Handler(Looper.getMainLooper());
executor.execute(new Runnable() {
@Override
public void run() {
load_json_from_url(target_url);
handler.post(new Runnable() {
@Override
public void run() {
if(actionListener!=null){
actionListener.get_string(result);
}
}
});
}
});
}
}
沒有留言:
張貼留言