HTTP通信(HttpURLConnection)

本文详细介绍了在Android中使用HttpURLConnection发送HTTP请求的具体步骤,包括如何创建URL对象、设置请求方式、配置连接超时及读取超时参数,并通过示例代码展示了如何获取服务器响应并处理。

 

Android发送HTTP请求有两种,HttpURLConnection和HttpClient
用法:
1.获取HttpURLConnection实例
new一个URL对象,传入一个网络地址;然后调用openConnection方法
 
2.设置HTTP请求的方法
常用的方法有两种:GET和POST方法,GET:从服务器获取数据;POST:发送数据给服务器
 
3.设置一些东西
比如设置连接超时,读取超时,服务器希望得到的消息头等
 
4.getInputStream获取服务器返回的输入流
 
5.对输入流进行读取
 
6.disconnect关闭HTTP连接

private void sendResquestWithURLConnection(){
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 reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while((line = reader.readLine()) != null){
response.append(line);
}
Message message = new Message();
message.what = SHOW_RESPONSE;

message.obj = response.toString();
handler.sendMessage(message);
}catch(Exception e){
e.printStackTrace();
}finally{
if (connection != null){
connection.disconnect();
}
}
}
}).start();

private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case SHOW_RESPONSE:
String response = (String)msg.obj;
responseText.setText(response);
}

}
};


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendRequest = (Button) findViewById(R.id.send_request);
responseText = (TextView) findViewById(R.id.response_text);
sendRequest.setOnClickListener(this);
}

@Override
public void onClick(View v) {
if (v.getId() == R.id.send_request){
sendResquestWithURLConnection();
}
}

转载于:https://www.cnblogs.com/aisi-liu/p/5344279.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值