android网络编程之HttpUrlConnection--POST请求

xiaoxiao2021-02-28  14

Http协议支持的操作有GET、POST、HEAD、PUT、TRACE、OPTIONS、DELETE,其中最最常用的还是GET和POST操作,本文基于服务器后台使用Servlet开发主要讲解一下HttpUrlConnection中的post请求

1. 网络开发不要忘记在配置文件中添加访问网络的权限

<uses-permission android:name="android.permission.INTERNET"/>

2. 网络请求、处理不能在主线程中进行,一定要在子线程中进行。因为网络请求一般有1~3秒左右的延时,在主线程中进行造成主线程的停顿,对用户体验来说是致命的。(主线程应该只进行UI绘制,像网络请求、资源下载、各种耗时操作都应该放到子线程中)。

public class PostActivity extends Activity { private TextView mTvMsg; private String result = null; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); setContentView(R.layout.activity_post); initView(); } private void initView(){ mTvMsg = (TextView) findViewById(R.id.tv_msg); new Thread(postThread).start(); } private Thread postThread = new Thread(){ public void run() { HttpURLConnection connection = null; try { URL url = new URL("http://192.168.23.1:8080/TestProject/PostTest"); connection = (HttpURLConnection) url.openConnection(); // 设置请求方式 connection.setRequestMethod("POST"); // 设置编码格式 connection.setRequestProperty("Charset", "UTF-8"); // 传递自定义参数 connection.setRequestProperty("MyProperty", "this is me!"); // 设置容许输出 connection.setDoOutput(true); // 上传一张图片 FileInputStream file = new FileInputStream(Environment.getExternalStorageDirectory().getPath() + "/Pictures/Screenshots/Screenshot_2015-12-19-08-40-18.png"); OutputStream os = connection.getOutputStream(); int count = 0; while((count=file.read()) != -1){ os.write(count); } os.flush(); os.close(); // 获取返回数据 if(connection.getResponseCode() == 200){ InputStream is = connection.getInputStream(); result = StringStreamUtil.inputStreamToString(is); Message msg = Message.obtain(); msg.what = 0; postHandler.sendMessage(msg); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if(connection!=null){ connection.disconnect(); } } }; }; private Handler postHandler = new Handler(){ public void handleMessage(android.os.Message msg) { if(msg.what==0 && result!=null){ mTvMsg.setText(result); } }; }; }

3. 上传Json字符串很长的话可以考虑将Json字符串作为字节流上传,不过要指明Json字符串的长度:Json的长度+Json+文件流。服务器端就可以根据Json的长度,区分Json和文件流。

4. 注意:上传大文件时,可能出现崩溃。我们可以设置一下HttpUrlConnection。

// 设置每次传输的流大小,可以有效防止手机因为内存不足崩溃 // 此方法用于在预先不知道内容长度时启用没有进行内部缓冲的 HTTP请求正文的流。 connection.setChunkedStreamingMode(51200); // 128K

5. 过程概述:

第一步:实例化URL对象。 第二步:实例化HttpUrlConnection对象。 第三步:设置请求连接属性,传递参数等。 第四步:获取返回码判断是否链接成功。 第五步:读取输入流。 第六步:关闭链接。
转载请注明原文地址: https://www.6miu.com/read-1100154.html

最新回复(0)