使用Http协议请求网络
16lz
2021-01-25
声明:笔者参考《第一行代码》一书!
在Android中,发送Http网络请求的方式一般有2种,HttpURLConnection和HttpClient。
下面先使用前者,代码如下:
先来看一下布局文件:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.yu.httpurlconnection.MainActivity"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="发送HTTP请求" android:id="@+id/send" android:layout_gravity="center_horizontal" /> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/scrollView" > <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/textview"/> </ScrollView></LinearLayout>
核心代码如下(HttpURLConnection):
public class MainActivity extends AppCompatActivity { private Button mSend; private TextView mTextView; Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { if(msg.what==1){ String text = (String) msg.obj; mTextView.setText(text); } super.handleMessage(msg); } }; private HttpURLConnection connection; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextView= (TextView) findViewById(R.id.textview); mSend= (Button) findViewById(R.id.send); mSend.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { sendHttp(); } }); } private void sendHttp() { //请求网络比较耗时,所以放在子线程中 new Thread(new Runnable() { @Override public void run() { try { URL uri = new URL("https://www.baidu.com/"); connection = (HttpURLConnection) uri.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); InputStream inputStream = connection.getInputStream(); StringBuilder sb = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while((line=reader.readLine())!=null){ sb.append(line); } Message message = new Message(); message.obj = sb.toString(); message.what = 1; handler.sendMessage(message); } catch (Exception e) { e.printStackTrace(); }finally { if(connection!=null){ connection.disconnect(); } } } }).start(); }}
下面用HttpClient:
PS:HttpClient好像被谷歌弃用了,所以想要使用它的话,导入jar包
public class MainActivity extends AppCompatActivity { private Button mSend; private TextView mTextView; Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { if(msg.what==2){ String text = (String) msg.obj; mTextView.setText(text); } super.handleMessage(msg); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextView= (TextView) findViewById(R.id.textview); mSend= (Button) findViewById(R.id.send); mSend.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { sendHttp(); } }); } private void sendHttp() { new Thread(new Runnable() { @Override public void run() { try { HttpClient mHttpClient = new DefaultHttpClient(); HttpGet mHttpGet =new HttpGet("https://www.baidu.com/"); HttpResponse response = mHttpClient.execute(mHttpGet); if(response.getStatusLine().getStatusCode()==200){ HttpEntity httpEntity = response.getEntity(); String result = EntityUtils.toString(httpEntity,"utf-8"); Message message = new Message(); message.obj = result; message.what=2; handler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); }finally { if(connection!=null){ connection.disconnect(); } } } }).start(); }}
运行效果:
更多相关文章
- 没有一行代码,「2020 新冠肺炎记忆」这个项目却登上了 GitHub 中
- Nginx系列教程(六)| 手把手教你搭建 LNMP 架构并部署天空网络电影
- android通过webservice验证用户 .
- StrictMode总结
- Eclipse下Android开发,如何查看 API源代码、私有库源代码 文件 (a
- android用户界面-组件Widget-常用组件
- network: Android(安卓)网络判断(wifi、3G与其他)
- Android如何防止apk程序被反编译
- RippleDrawable 触摸反馈 ---- java 代码编写