关闭

HttpURLConnection请求网络小练习

148人阅读 评论(0) 收藏 举报
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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:4601次
    • 积分:105
    • 等级:
    • 排名:千里之外
    • 原创:5篇
    • 转载:8篇
    • 译文:0篇
    • 评论:0条
    文章存档