HttpURLConnection请求网络小练习

package com.example.day_04_httpurlconnection;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;


public class MainActivity extends Activity {


private TextView textView;



Handler handler=new Handler(){
public void handleMessage(android.os.Message msg) {

String data = (String) msg.obj;
textView.setText(data);
};


};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

textView = (TextView) findViewById(R.id.textView);


new Thread() {


public void run() {
getData();
};


}.start();

}


/**
* 联网请求数据
*/
private void getData() {
try {

//得到URL对象,并设置访问地址
URL url=new URL("http://www.baidu.com/");
//得到HttpURLConnection对象
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
//设置连接超时
httpURLConnection.setConnectTimeout(5000);
//设置请求方式 get/post
httpURLConnection.setRequestMethod("POST");
//读取超时
httpURLConnection.setReadTimeout(5000);

//正式联网
httpURLConnection.connect();
//获得状态码
int code =httpURLConnection.getResponseCode();

if(code==200){

System.out.println("联网请求成功");

//获取包含数据的输入流
InputStream inputStream = httpURLConnection.getInputStream();

BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
//记录每一行读取的数据
String data;
//拼接字符串
StringBuffer stringBuffer=new StringBuffer();
while ((data=bufferedReader.readLine())!=null) {
stringBuffer.append(data);

}


/* System.out.println(stringBuffer.toString());

textView.setText(stringBuffer.toString());*/

Message msg = Message.obtain();
msg.obj=stringBuffer.toString();
handler.sendMessage(msg);

}else{

System.out.println("联网失败");

}




} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}






}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值