Android开发HttpURLConnection网络请求
发布日期:2021-06-30 11:20:22 浏览次数:2 分类:技术文章

本文共 3811 字,大约阅读时间需要 12 分钟。

 

activity_main 

 

 MainActivity

package com.etime.myproject;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.View;import android.widget.Button;import android.widget.TextView;import androidx.annotation.NonNull;import java.io.BufferedReader;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;/** * 网络请求需添加权限 * 
*/public class MainActivity extends Activity { private TextView mResponseTextView; private Button mSendRequestButton; private Handler mHandler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); } private void init(){ //创建Handler mHandler=new MyHandler(); mResponseTextView = (TextView) findViewById(R.id.responseTextView); mSendRequestButton = (Button) findViewById(R.id.sendRequestButton); mSendRequestButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { MyThread myThread=new MyThread(); myThread.start(); } }); } private class MyHandler extends Handler{ @Override public void handleMessage(@NonNull Message msg) { super.handleMessage(msg); //处理消息 int what=msg.what; if(what==1){ String message=(String)msg.obj; //更新UI mResponseTextView.setText(message); } } } private class MyThread extends Thread{ @Override public void run() { super.run(); HttpURLConnection connection = null; InputStream is=null; ByteArrayOutputStream bos=null; try { //创建URL URL url = new URL("https://www.baidu.com/"); //打开链接 connection = (HttpURLConnection) url.openConnection(); //设置请求方式 connection.setRequestMethod("GET"); //建立链接 connection.connect(); //获取响应码 int responseCode=connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { //读取数据 is = connection.getInputStream(); bos = new ByteArrayOutputStream(); int len = 0; byte buffer[] = new byte[1024*2]; while ((len = is.read(buffer)) != -1) { bos.write(buffer, 0, len); } //处理数据 String response = new String(bos.toByteArray()); //创建消息 Message message=new Message(); message.what=1; message.obj=response; //发送消息 mHandler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } finally { //释放资源 if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (bos != null) { try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } if (connection != null) { connection.disconnect(); } } } }}

 

AndroidManifest.xml

 

转载地址:https://it9527.blog.csdn.net/article/details/8195243 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Android常用控件之Button
下一篇:Android常用控件之TextView

发表评论

最新留言

路过按个爪印,很不错,赞一个!
[***.219.124.196]2024年04月19日 00时59分34秒