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}

待补充

欢迎指错,一起学习

相关推荐
zhensherlock15 分钟前
Protocol Launcher 系列:1Writer iOS 上的 Markdown 文档管理
javascript·笔记·ios·typescript·node.js·iphone·ipad
EmmaXLZHONG29 分钟前
Django By Example - 学习笔记
笔记·python·学习·django
Gse0a362g42 分钟前
推荐 PHP 属性(Attributes) 简洁读取 API 扩展包
android·开发语言·php
prog_610344 分钟前
【笔记】用cursor手搓cursor(五)再见claude
人工智能·笔记·大语言模型·agent
十六年开源服务商1 小时前
WordPress服务器响应时间优化终极指南2026
android·运维·服务器
扑火的小飞蛾1 小时前
OpenClaw Dashboard 部署与远程访问笔记
笔记
jwn9991 小时前
PHP vs Go:后端开发选谁更胜一筹?
android
Engineer邓祥浩2 小时前
JVM学习笔记(5) 第二部分 自动内存管理 第4章 虚拟机性能监控、故障处理工具
jvm·笔记·学习
Vfw3VsDKo2 小时前
Android设备搭建本地RTSP服务器(基于live555)
android·运维·服务器
九狼JIULANG2 小时前
【无标题】
android·flutter·开源·github