package com.pingyijinren.test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by Administrator on 2016/5/19 0019.
*/
public class HttpUtil {
public interface HttpCallbackListener{
void onFinish(String response);
void onError(Exception e);
}
public static void sendHttpRequest(final String address,final HttpCallbackListener listener){ //子线程中无法返回数据,所以要使用接口
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection=null;
try{
URL url=new URL(address);
connection=(HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
connection.setDoInput(true);
connection.setDoOutput(true);
InputStream in=connection.getInputStream();
BufferedReader reader=new BufferedReader(new InputStreamReader(in));
StringBuilder response=new StringBuilder();
String line;
while((line=reader.readLine())!=null){
response.append(line);
}
if(listener!=null){
listener.onFinish(response.toString());
}
}
catch(Exception e){
if(listener!=null){
listener.onError(e);
}
}
finally {
if(connection!=null){
connection.disconnect();
}
}
}
}).start();
}
}
package com.pingyijinren.test;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity{
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String address="http://www.runoob.com";
HttpUtil.sendHttpRequest(address, new HttpUtil.HttpCallbackListener() {
@Override
public void onFinish(String response) {
Log.d("MainActivity",response); //更新UI还是要使用异步消息处理机制
}
@Override
public void onError(Exception e) {
e.printStackTrace();
Log.d("MainActivity",e.getMessage());
}
});
}
});
}
}