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+ “×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();
        }
    }
}

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>

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>

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}

你可能感兴趣的:(Android,android,studio,笔记,android)