zoukankan
html css js c++ java
安卓中使用HttpURLConnection连接网络简单示例 --Android网络编程
MainActivity.java:
package thonlon.example.cn.httpurlconnectionpro;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
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;
public class MainActivity extends AppCompatActivity {
private Button btn_req;
private TextView tv_res;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
btn_req = (Button) findViewById(R.id.btn_req);
tv_res = (TextView) findViewById(R.id.tv_res);
}
public void onClick(View view) {
sendRequestHttpURLConnection();
}
public void sendRequestHttpURLConnection() {
new Thread(new Runnable() {
@Override
public void run() {
String urlStr = "https://www.baidu.com";
HttpURLConnection conn = null;
BufferedReader reader = null;
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(8000);
conn.setReadTimeout(8000);
InputStream is = conn.getInputStream();
reader = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
response.append(line);
}
showResponse(response.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (conn != null) {
conn.disconnect();
}
}
}
}).start();
}
private void showResponse(final String response) {
runOnUiThread(new Runnable() {
@Override
public void run() {
tv_res.setText(response);
}
});
}
}
查看全文
相关阅读:
Linux下关于信号block与unblock的小研究
perl打印乘法表
Linux下libaio的一个简单例子
heritrix的简单使用以及在后台调用heritrix
perl修改文件内容
Linux下mmap函数的一个练习
Linux real uid 和 effective uid相关总结
阶段性小总结
归并排序的一个练习
利用openssl进行base64的编码与解码
原文地址:https://www.cnblogs.com/qikeyishu/p/9172595.html
最新文章
ADO.NET Entity Framework学习笔记(1)介绍
用Minify加快你的网站速度
恢复误删数据(SQL Server 2000)--Log Explorer
ADO.net,Linq to SQL和Entity Framework性能实测分析
超酷的Flash 3D图片幻灯片特效– cu3er
JAVA获取本地ip地址
ECharts 之 环形图
海康摄像头的二次开发(java)
大华摄像头java开发之预览
ECharts 之 堆叠柱状图
热门文章
大华摄像头java开发之抓图
邮件发送工具类
【原创+史上最全】Nginx+ffmpeg实现流媒体直播点播系统
EasyUi+Spring Data 实现按条件分页查询
JAVA设计模式初探之装饰者模式
centos6.7下安装mysql5.6.22同时解决中文乱码问题
EasyUI+zTree实现简单的树形菜单切换
maven阿里云中央仓库
悲观锁和乐观锁
实现百度分页效果的工具类
Copyright © 2011-2022 走看看