【问题标题】:How to change a HttpsURLConnection GET to be a POST request?如何将 HttpsURLConnection GET 更改为 POST 请求?
【发布时间】:2021-11-01 04:03:39
【问题描述】:

我真的是 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" );

但是我怎样才能传递参数呢?

【问题讨论】:

  • 首先你需要改变的是 mUrlConnection.setRequestMethod( "GET" );到 mUrlConnection.setRequestMethod("POST");
  • 这个网址会帮助你。 baeldung.com/httpurlconnection-post
  • 您想要 JSON 格式吗?表示键和值?
  • @VatsalDholakiya Yes sr
  • 所以,请发布您的参数名称。

标签: java android request http-post httpsurlconnection


【解决方案1】:

试试这样的:

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();

【讨论】:

    【解决方案2】:

    你几乎明白了。试试这个,它应该工作。我使用 Jackson 从 Map 中获取 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;
        }
        
    }
    

    【讨论】:

      【解决方案3】:

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

      第 1 步: 在 Gradle 文件中添加 gson 依赖项。

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

      第 2 步:为您的参数/键创建一个模型类。

      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 步: 创建模型类的对象并添加值。

      //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();
      

      【讨论】:

        猜你喜欢
        • 2018-01-10
        • 2021-01-16
        • 2017-01-31
        • 2020-07-14
        • 2023-01-11
        • 2019-10-04
        • 1970-01-01
        • 1970-01-01
        • 2012-01-13
        相关资源
        最近更新 更多