简体   繁体   English

在java中使用HttpURLConnection发送带有GET请求的请求正文

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

Kindly don't confuse my question with sending body with POST request using HttpURLConnection.请不要将我的问题与使用 HttpURLConnection 发送正文与 POST 请求混淆。

I want to send body with GET request using HttpURLConnection.我想使用 HttpURLConnection 发送带有 GET 请求的正文。 Here is code i am using.这是我正在使用的代码。

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;
}

what happens is that the request type is identified automatically depending on the connection.getInputStream() and connection.getOutPutStream().发生的情况是根据connection.getInputStream()connection.getOutPutStream()自动识别请求类型

when you call connection.getOutPutStream() the request type is automatically set to POST even if you have explicitly set request type to GET using connection.setRequestMethod("GET") .当您调用connection.getOutPutStream() 时,即使您已使用connection.setRequestMethod("GET")将请求类型显式设置为GET ,请求类型也会自动设置为POST

The problem is that i am using 3rd party Web Service(API) which accepts request parameters as body with GET request问题是我正在使用第 3 方 Web 服务(API),它接受请求参数作为带有 GET 请求的主体

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

<response>
{json}

I am well aware that most of the case GET don't have request body but many of the web service often uses GET request with parameters as body instead of query string.我很清楚大多数情况下 GET 没有请求正文,但许多 Web 服务经常使用 GET 请求作为正文而不是查询字符串作为参数。 Kindly guide me how i can send GET request with body in android without using any 3rd party library(OkHttp,Retrofit,Glide etc)请指导我如何在不使用任何 3rd 方库(OkHttp、Retrofit、Glide 等)的情况下在 android 中发送带有正文的 GET 请求

use this code you will need to do a little modification but it will get the job done.使用此代码,您需要做一些修改,但它会完成工作。

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

this the Raw HTTP Request Dump这是原始 HTTP 请求转储

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

parameter1=value&parameter2=value2

Note : This is for http request if you want https Connection Please refer to the link SSLSocketClient注意:这是用于http请求,如果你想要https连接请参考链接SSLSocketClient

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM