如何将 HttpsURLConnection GET 更改为 POST 请求?

How to change a HttpsURLConnection GET to be a POST request?

我真的是 android(一般编程)的新手,但我继承了另一个人创建的项目,我知道这对你们很多人来说可能很简单,但我尝试更改以下代码时迷路了。

我需要做的是将请求类型从 GET 更改为 POST,并随请求发送一些值。

请求需要具有以下语法。

type=active
data={"json here with all info"} ------> mRequestStringEncoded


String RequestString = ((myrequest) request).getJson();
String mRequestStringEncoded = URLEncoder.encode( RequestString, "utf-8" );
mURL = defautlUrl+ mRequestStringEncoded;
Log.e( TAG, "Request URL: " + mURL );
 

try
{
    HttpsURLConnection mUrlConnection = (HttpsURLConnection) new URL( mURL ).openConnection();

    mUrlConnection.setRequestProperty( "charset", "utf-8" );
    mUrlConnection.setRequestMethod( "GET" ); 
    mUrlConnection.setConnectTimeout( 12000 );
    mUrlConnection.setReadTimeout( 30000 );
    mUrlConnection.connect();

我知道我需要改变:

mUrlConnection.setRequestProperty( "charset", "utf-8" );
mUrlConnection.setRequestMethod( "GET" ); 

收件人:

mUrlConnection.setRequestProperty("Content-Type", "application/json; utf-8");
mUrlConnection.setRequestMethod( "POST" );

但是如何传递参数呢?

你差不多明白了。试试这个,它应该工作。我使用 Jackson 从地图中获取 json 格式:

package com.http;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class FormSubmitService {

    public void doSubmit(String url, Map<String, String> data) throws IOException {
        URL siteUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) siteUrl.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json; utf-8");
        conn.setUseCaches (true);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        String content = getJsonFromMap(data);
        System.out.println(content);
        out.writeBytes(content);
        out.flush();
        out.close();
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line = "";
        while ((line=in.readLine())!=null) {
            System.out.println(line);
        }
        in.close();
    }
    
    private String getJsonFromMap(Map<String, String> map) {
        ObjectMapper objectMapper = new ObjectMapper();
        String json = null;
        try {
            json = objectMapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return json;
    }
    
}

那么,在 POST 方法中,您可以通过使用 Gson 将参数转换为 JSON 来传递参数。

第一步:在Gradle文件中添加gson依赖

dependencies {
  implementation 'com.google.code.gson:gson:2.8.8'
}

第 2 步: 为您的 parameter/key 创建模型 class。

public class ApiModel {

  public String type,data;

  public ApiModel(String type, String data) {
    this.type = type;
    this.data = data;
  }

  public String getType() {
    return type;
  }

  public String getData() {
    return data;
  }
}

步骤 3: 创建模型对象 class 并添加值。

//add data into model to create json
ApiModel ObjApi = new ApiModel(type_value, data_value);

第 4 步: 现在,使用 Gson 将 ObjApi 转换为 JSON。

Gson gson = new Gson();
String json = gson.toJson(ObjApi);

第 5 步: 添加 json 字符串到 BufferedWriter.

 OutputStream stream = httpURLConnection.getOutputStream();
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(stream, "UTF-8"));
        bufferedWriter.write(json);
        bufferedWriter.flush();
        bufferedWriter.close();
        stream.close();

示例: 使用 httpurlConnection 的示例。

  HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestMethod(REQUEST_METHOD);
        httpURLConnection.setRequestProperty("Content-Type", "application/json");
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setConnectTimeout(TimeOut);
        httpURLConnection.setReadTimeout(TimeOut);
        OutputStream stream = httpURLConnection.getOutputStream();
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(stream, "UTF-8"));
        bufferedWriter.write(json);
        bufferedWriter.flush();
        bufferedWriter.close();
        stream.close();
        httpURLConnection.disconnect();

尝试这样的事情:

String post_data="type=active&data=" + data;

  HttpsURLConnection mUrlConnection = (HttpsURLConnection) new URL( tURL ).openConnection();
  mUrlConnection.setRequestMethod( "POST" );

  mUrlConnection.setRequestProperty("type", "active");
  mUrlConnection.setRequestProperty("data", "data"); 
  mUrlConnection.setDoOutput(true);

  //Adding Post Data
  OutputStream outputStream = mUrlConnection.getOutputStream();
  outputStream.write(post_data.getBytes());
  outputStream.flush();
  outputStream.close();


  mUrlConnection.setConnectTimeout( 22000 );
  mUrlConnection.setReadTimeout( 30000 );
  mUrlConnection.connect();