• Android Studio的笔记--HttpsURLConnection使用POST请求


    https post请求加返回

    MainActivity.java

    用HttpsURLConnection POST方法进行需注意:
    1、Android 9及以上版本需要设置这个,否则会有警告
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    }
    2、清单中要申请网络权限
    < uses-permission android:name=“android.permission.INTERNET” />
    3、关于请求
    设置连接请求方式:setRequestMethod(“POST”)
    设置传入参数的格式:setRequestProperty(“Content-Type”, “application/x-www-form-urlencoded”)
    设置鉴权信息:setRequestProperty(“Authorization”, “Bearer " + key);
    请求头transactionid:setRequestProperty(“transactionid”, transactionid);
    请求体:“areaNo=” + areano+ “mac=” + mac+ “&romVersion=” + romVersion+ “×tamp=”+ timestamp+ “&sign=” + sign;
    4、响应格式
    {“result”:-1,“msg”:“抱歉)”,“fileUrl”:”“,“fileMD5”:”“,“versionName”:”",“timestamp”:169xxx}
    整体如下

    package com.lxh.romupgrade;
    import androidx.appcompat.app.AppCompatActivity;
    import android.content.Context;
    import android.os.Build;
    import android.os.Bundle;
    import android.os.StrictMode;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import org.json.JSONException;
    import org.json.JSONObject;
    import java.io.BufferedReader;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.URL;
    import java.net.URLDecoder;
    import javax.net.ssl.HttpsURLConnection;
    public class MainActivity extends AppCompatActivity {
        Button bt_post;
        Button bt_post2;
        Context mcontext;
        private static final String TAG = "MainActivity3 lxh";
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            bt_post = findViewById(R.id.bt_post);
            bt_post2 = findViewById(R.id.bt_post2);
            mcontext = MainActivity.this;
            bt_post.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Log.i(TAG, "onClick");
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                        StrictMode.setThreadPolicy(policy);
                    }
                    post_RomUp();
                }
            });
        }
    
        public void post_RomUp() {
            try {
                Log.i(TAG, "post_RomUp");
                URL obj = new URL(getRomUpgradePolicy_url);
                HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
                con.setRequestMethod("POST");
                con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                con.setRequestProperty("transactionid", transactionid);
                //假设使用Bearer令牌认证方式,将密钥添加到请求头中
                con.setRequestProperty("Authorization", "Bearer " + key);
                String bodyParams = "areaNo=" + areano
                        + "mac=" + mac
                        + "&romVersion=" + romVersion
                        + "×tamp=" + timestamp
                        + "&sign=" + sign;
                con.setDoOutput(true);
                DataOutputStream wr = new DataOutputStream(con.getOutputStream());
                wr.writeBytes(bodyParams);
                wr.flush();
                wr.close();
                int responseCode = con.getResponseCode();
                Log.i(TAG, "responseCode=" + con.getResponseCode());//200
                Log.i(TAG, "getRequestMethod=" + con.getRequestMethod());//POST
                Log.i(TAG, "getDate=" + con.getDate());//
                Log.i(TAG, "toString=" + con.toString());//com.android.okhttp.internal.huc.HttpURLConnectionImpl:https://
                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                Log.i(TAG, URLDecoder.decode(response.toString(), "UTF-8"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81

    AndroidMainfest.xml

    需要在清单添加

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.lxh.romupgrade">
         <uses-permission android:name="android.permission.INTERNET" />
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/Theme.Romupgrade">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    </manifest>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    activity_main.xml

    布局如下

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
        <Button
            android:id="@+id/bt_post"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="POST" />
        <Button
            android:id="@+id/bt_post2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="POST2" />
    </LinearLayout>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    log

    点击按钮回显如下

    I/MainActivity3 lxh: onClick
    I/MainActivity3 lxh: post_RomUp
    D/NetworkSecurityConfig: No Network Security Config specified, using platform default
    I/MainActivity3 lxh: responseCode=200
    I/MainActivity3 lxh: getRequestMethod=POST
    I/MainActivity3 lxh: getDate=
    I/MainActivity3 lxh: toString=com.android.okhttp.internal.huc.HttpURLConnectionImpl:https://
    I/MainActivity3 lxh: {"result":-1,"msg":"抱歉","fileUrl":"","fileMD5":"","versionName":"","timestamp":169xxx}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    待补充
    欢迎指错,一起学习

  • 相关阅读:
    C++友元函数
    TCP协议
    2022年十大数据泄露事件
    ArduPilot开源代码之H743+BMI270x2+ChibiOS配置适配
    MySQL触发器
    《Web安全基础》06. 逻辑漏洞&越权
    两日总结七
    KFC Crazy Thursday---马拉车/二分+字符串哈希
    【星球】【slam】研讨会(4)你真的适合读博吗?
    [MQ] 死信队列介绍与场景描述
  • 原文地址:https://blog.csdn.net/weixin_45208598/article/details/133763757