簡體   English   中英

在java中使用HttpURLConnection發送帶有GET請求的請求正文

[英]Send request body with GET request using HttpURLConnection in java

請不要將我的問題與使用 HttpURLConnection 發送正文與 POST 請求混淆。

我想使用 HttpURLConnection 發送帶有 GET 請求的正文。 這是我正在使用的代碼。

public static String makeGETRequest(String endpoint, String encodedBody) {
    String responseJSON = null;
    URL url;
    HttpURLConnection connection;

    try {
        url = new URL(endpoint);
        connection = (HttpURLConnection) url.openConnection();

        connection.setInstanceFollowRedirects(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        connection.connect();
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(encodedBody.getBytes());
        outputStream.flush();

        Util.log(connection,connection.getResponseCode()+":"+connection.getRequestMethod());

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String responseChunk = null;
        responseJSON = "";
        while ((responseChunk = bufferedReader.readLine()) != null) {
            responseJSON += responseChunk;
        }

        bufferedReader.close();
        connection.disconnect();

    } catch (Exception e) {
        e.printStackTrace();
        Util.log(e, e.getMessage());
    }

    return responseJSON;
}

發生的情況是根據connection.getInputStream()connection.getOutPutStream()自動識別請求類型

當您調用connection.getOutPutStream() 時,即使您已使用connection.setRequestMethod("GET")將請求類型顯式設置為GET ,請求類型也會自動設置為POST

問題是我正在使用第 3 方 Web 服務(API),它接受請求參數作為帶有 GET 請求的主體

<get-request>
/myAPIEndPoint
body = parameter1=value as application/x-www-form-urlencoded

<response>
{json}

我很清楚大多數情況下 GET 沒有請求正文,但許多 Web 服務經常使用 GET 請求作為正文而不是查詢字符串作為參數。 請指導我如何在不使用任何 3rd 方庫(OkHttp、Retrofit、Glide 等)的情況下在 android 中發送帶有正文的 GET 請求

使用此代碼,您需要做一些修改,但它會完成工作。

package com.kundan.test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

public class GetWithBody {

    public static final String TYPE = "GET ";
    public static final String HTTP_VERSION = " HTTP/1.1";
    public static final String LINE_END = "\r\n";

    public static void main(String[] args) throws Exception {
        Socket socket = new Socket("localhost", 8080); // hostname and port default is 80
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write((TYPE + "<Resource Address>" + HTTP_VERSION + LINE_END).getBytes());// 
        outputStream.write(("User-Agent: Java Socket" + LINE_END).getBytes());
        outputStream.write(("Content-Type: application/x-www-form-urlencoded" + LINE_END).getBytes());
        outputStream.write(LINE_END.getBytes()); //end of headers
        outputStream.write(("parameter1=value&parameter2=value2" + LINE_END).getBytes()); //body 
        outputStream.flush();

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        StringBuilder builder = new StringBuilder();
        String read = null;
        while ((read = bufferedReader.readLine()) != null) {
            builder.append(read);
        }

        String result = builder.toString();
        System.out.println(result);
    }
}

這是原始 HTTP 請求轉儲

GET <Resource Address> HTTP/1.1
User-Agent: Java Socket
Content-Type: application/x-www-form-urlencoded

parameter1=value&parameter2=value2

注意:這是用於http請求,如果你想要https連接請參考鏈接SSLSocketClient

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM