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

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+ "&timestamp="+ timestamp+ "&sign=" + sign;

4、响应格式

{"result":-1,"msg":"抱歉)","fileUrl":"","fileMD5":"","versionName":"","timestamp":169xxx}

整体如下

java 复制代码
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
                    + "&timestamp=" + 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();
        }
    }
}

AndroidMainfest.xml

需要在清单添加

java 复制代码
<?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>

activity_main.xml

布局如下

java 复制代码
<?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>

log

点击按钮回显如下

java 复制代码
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}

待补充

欢迎指错,一起学习

相关推荐
SRC_BLUE_171 小时前
SQLI LABS | Less-39 GET-Stacked Query Injection-Intiger Based
android·网络安全·adb·less
2401_858286113 小时前
L7.【LeetCode笔记】相交链表
笔记·leetcode·链表
无尽的大道4 小时前
Android打包流程图
android
龙中舞王5 小时前
Unity学习笔记(2):场景绘制
笔记·学习·unity
青椒大仙KI116 小时前
24/11/7 算法笔记 PCA主成分分析
笔记·算法·信息可视化
镭封6 小时前
android studio 配置过程
android·ide·android studio
夜雨星辰4876 小时前
Android Studio 学习——整体框架和概念
android·学习·android studio
邹阿涛涛涛涛涛涛6 小时前
月之暗面招 Android 开发,大家快来投简历呀
android·人工智能·aigc
光明中黑暗6 小时前
机器学习 笔记
人工智能·笔记·机器学习
IAM四十二6 小时前
Jetpack Compose State 你用对了吗?
android·android jetpack·composer