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);
}
});
}
}
查看全文
相关阅读:
(转)关于c#中的事件
MySql数据库--持续记录ing
在Eclipse中通过JDBC连接MySQL步骤,非常详细!
mybatis传入参数类型parameterType和输出结果类型resultType详解
关于JDBC访问存储过程的问题
Mybatis(一)入门
[Redis] 基于redis的分布式锁
分布式锁----浅析redis实现
MyBatis的增删改查操作
C3P0连接池工具类实现步骤及方法
原文地址:https://www.cnblogs.com/qikeyishu/p/9172595.html
最新文章
学习tornado:安全
.Net多线程之线程安全
排序
使用lombok提高编码效率
⑩ 设计模式的艺术-23.解释器(Interpreter)模式
⑨ 设计模式的艺术-22.中介者(Mediator)模式
⑧ 设计模式的艺术-21.迭代器(Iterator)模式
⑦ 设计模式的艺术-20.备忘录(Memento)模式
⑥ 设计模式的艺术-19.命令(Command)模式
⑤ 设计模式的艺术-18.策略(Strategy)模式
热门文章
④ 设计模式的艺术-17.模板方法(Template Method)模式
(转)asp.net基础-HttpModule
Repeater事件OnItemCommand取得行内控件
(转)HttpHandler与HttpModule的理解与应用
js正则表达式中/=s*".*?"/g表示什么意思?
(转)Asp.NetURL重写的一种方法
(转)ASP.net的url重写
(转) ASP.NET反射
./和../以及/之间的区别?
Container.ItemIndex 获取到行的序号
Copyright © 2011-2022 走看看