Android(安卓)HTTP请求
16lz
2021-12-04
Android HTTP请求
直接上代码:
代码中有GET和POST两种方法:
package com.example.camera.demohttp;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Handler;import android.os.HandlerThread;import android.os.Looper;import android.os.Message;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.ImageView;import android.widget.Toast;import java.io.BufferedInputStream;import java.io.BufferedReader;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;public class MainActivity extends AppCompatActivity implements View.OnClickListener { private HandlerThread handlerThread; private Handler handler; private ImageView imageView; private final int DOWNDLOAD = 1; private final int REGISTER = 2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.downloadFile).setOnClickListener(this); findViewById(R.id.register).setOnClickListener(this); imageView = findViewById(R.id.img); handlerThread = new HandlerThread("http"); handlerThread.start(); handler = new HttpHandler(handlerThread.getLooper());//让handler消息运行子线程 } @Override public void onClick(View v) { switch (v.getId()) { case R.id.downloadFile: handler.sendEmptyMessage(DOWNDLOAD); break; case R.id.register: handler.sendEmptyMessage(REGISTER); break; default: break; } } private class HttpHandler extends Handler { public HttpHandler(Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { switch (msg.what) { case DOWNDLOAD: downloadFile(); break; case REGISTER: registerUser(); break; default: break; } } } //post请求 private void registerUser() { String registerUrl = "http://169.254.230.253:8080/register"; try { URL url = new URL(registerUrl); HttpURLConnection postConnection = (HttpURLConnection) url.openConnection(); postConnection.setRequestMethod("POST");//post 请求 postConnection.setConnectTimeout(1000*5); postConnection.setReadTimeout(1000*5); postConnection.setDoInput(true);//允许从服务端读取数据 postConnection.setDoOutput(true);//允许写入 postConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");//以表单形式传递参数 String postParms = "name=1702C2019&password=12345&verifyCode=8888"; OutputStream outputStream = postConnection.getOutputStream(); outputStream.write(postParms.getBytes());//把参数发送过去. outputStream.flush(); final StringBuffer buffer = new StringBuffer(); int code = postConnection.getResponseCode(); if (code == 200) {//成功 InputStream inputStream = postConnection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String line = null;//一行一行的读取 while ((line = bufferedReader.readLine()) != null) { buffer.append(line);//把一行数据拼接到buffer里 } runOnUiThread(new Runnable() { @Override public void run() { //把从服务端获取的数据提示出来 Toast.makeText(MainActivity.this, buffer.toString(), Toast.LENGTH_SHORT).show(); } }); } } catch (Exception e) { e.printStackTrace(); } } //需要放到子线程中去,使用handlerThread. private void downloadFile() { String downloadUrl = "http://pic41.nipic.com/20140508/18609517_112216473140_2.jpg"; String savePath = "/sdcard/flowergirl.jpg"; File file = new File(savePath); if (file.exists()) { file.delete();//如果文件存在,先删掉 } BufferedInputStream bufferedInputStream = null; FileOutputStream outputStream = null; try { URL url = new URL(downloadUrl); try { HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("GET"); httpURLConnection.setConnectTimeout(1000*5); httpURLConnection.setReadTimeout(1000*5); httpURLConnection.setDoInput(true); httpURLConnection.connect(); //代表请求成功 if (httpURLConnection.getResponseCode() == 200) { InputStream in = httpURLConnection.getInputStream(); bufferedInputStream = new BufferedInputStream(in);//文件输入流 outputStream = new FileOutputStream(savePath); byte[] buffer = new byte[1024]; int length = 0; while ((length = bufferedInputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, length);//写入文件 } outputStream.flush();//强制把数据写入磁盘 final Bitmap bitmap = BitmapFactory.decodeFile(savePath); runOnUiThread(new Runnable() { @Override public void run() { imageView.setImageBitmap(bitmap); } }); } } catch (IOException e) { e.printStackTrace(); } } catch (MalformedURLException e) { e.printStackTrace(); } finally { try { if (bufferedInputStream!= null) { bufferedInputStream.close(); } if (outputStream != null) { outputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } }}
更多相关文章
- Android文件存储
- Android(安卓)解码MediaCodec 播放H264 265
- Android(安卓)Application 之 allowBackup 属性浅析
- Android(安卓)app自动更新总结(已适配9.0)
- Android通过http协议POST传输方式(输出流提交到服务端)
- 学习心得(二)
- 在Android中查看和管理sqlite数据库
- Android系列教程之十:Intents and Intent Filters(一)
- android SQLite的使用