import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
public static final int SHOW_RESPONSE = 0;
private Button sendResquest;
private TextView responseText;
MyHandler handler = new MyHandler(this);
static class MyHandler extends Handler{
WeakReference<MainActivity> mActivity;
MyHandler(MainActivity mainActivity){
mActivity = new WeakReference<MainActivity>(mainActivity);
}
@Override
public void handleMessage(Message msg) {
MainActivity activity = mActivity.get();
switch (msg.what){
case SHOW_RESPONSE:
String response = (String)msg.obj;
activity.responseText.setText(response);
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendResquest = (Button)findViewById(R.id.send_requset);
responseText = (TextView)findViewById(R.id.response_text);
sendResquest.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId()==R.id.send_requset){
sendRequsetWithHttpURLConnection();
}
}
private void sendRequsetWithHttpURLConnection(){
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
try {
URL url = new URL("http://www.baidu.com");
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
InputStream in = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line;
while((line = br.readLine())!=null){
sb.append(line);
}
Message message = new Message();
message.what = SHOW_RESPONSE;
message.obj = sb.toString();
handler.sendMessage(message);
}catch (Exception e){
e.printStackTrace();
}
finally {
if (connection!=null){
connection.disconnect();
}
}
}
}).start();
}
}
使用HttpURLConnection发送HTTP请求
最新推荐文章于 2024-04-26 17:12:21 发布