当前位置: 首页 > news >正文

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

HttpsURLConnection使用POST请求

  • https post请求加返回
    • MainActivity.java
    • AndroidMainfest.xml
    • activity_main.xml
    • log

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}
整体如下

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";@Overrideprotected 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() {@Overridepublic 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());//200Log.i(TAG, "getRequestMethod=" + con.getRequestMethod());//POSTLog.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

需要在清单添加

<?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" /><applicationandroid: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

布局如下

<?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"><Buttonandroid:id="@+id/bt_post"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:text="POST" /><Buttonandroid:id="@+id/bt_post2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:text="POST2" />
</LinearLayout>

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}

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

http://www.lryc.cn/news/192901.html

相关文章:

  • win redis 配置自启动服务
  • 走进Spark
  • “小程序:改变电商行业的新趋势“
  • Python与CAD系列基础篇(五)创建图案填充
  • 终端仿真软件连接交换机调试步骤
  • redis基本数据类型
  • C++笔记之std::async的用法
  • OpenCV4(C++)—— 图像连通域的详细分析
  • Rule-Engine-Starter V1.0.0
  • 绘制X-Bar-S和X-Bar-R图,监测过程,计算CPK过程能力指数
  • 【每日一句】只出现一次的数
  • GDB调试程序常用命令
  • C语言,求两个数的二进制表达中,有多少个位数不同
  • 解决Win10电脑无线网卡的移动热点无法开启问题
  • Spring framework Day10:JSR330注入注解
  • Java开发中List数据量大,需要分片批次处理
  • Apache Doris 2.0.2 版本正式发布!
  • transformers架构实现
  • C++类型推导
  • Open3D(C++) SVD分解求两个点云的变换矩阵
  • rtmp htttp推流Windows桌面到srs进行播放
  • NSSCTF做题(9)
  • 【09】基础知识:React组件的生命周期
  • Pytorch之ConvNeXt图像分类
  • Linux系统编程:makefile以及文件系统编程
  • 《动手学深度学习 Pytorch版》 8.5 循环神经网络的从零开始实现
  • 写一个宏,可以将一个整数的二进制位的奇数位和偶数位交换
  • Zabbix监控系统详解2:基于Proxy分布式实现Web应用监控及Zabbix 高可用集群的搭建
  • docker 安装oracle
  • C++ vector 自定义排序规则(vector<vector<int>>、vector<pair<int,int>>)