工具类
public class DsdUtil {
public DsdUtil () {
}
public interface httpGetCallback {
void onResult(String ret);
}
public static void httpGet (String url, final httpGetCallback listener) {
AsyncTask<String, Void, String> task = new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground (String... params ) {
URL urlPath;
try {
urlPath = new URL(params [0 ]);
HttpURLConnection httpURLConnection = (HttpURLConnection) urlPath.openConnection();
httpURLConnection.setConnectTimeout(3000 );
httpURLConnection.setReadTimeout(3000 );
httpURLConnection.connect();
InputStream inputStream = null ;
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
inputStream = httpURLConnection.getInputStream();
} else {
return null ;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null ) {
response.append(line);
}
return response.toString();
} catch (IOException e) {
e.printStackTrace();
return null ;
}
}
protected void onPostExecute (String ret) {
listener.onResult(ret);
}
};
task.execute(url);
}
}
使用
DsdUtil.httpGet("http://www.baidu.com" , new DsdUtil.httpGetCallback() {
@Override
public void onResult (String ret) {
}
});