Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在java中使用HttpURLConnection发送请求正文和获取请求_Java_Android_Api_Web Services_Get - Fatal编程技术网

在java中使用HttpURLConnection发送请求正文和获取请求

在java中使用HttpURLConnection发送请求正文和获取请求,java,android,api,web-services,get,Java,Android,Api,Web Services,Get,请不要将我的问题与使用HttpURLConnection发送带有POST请求的正文混淆。 我想使用HttpURLConnection发送带有GET请求的正文。这是我正在使用的代码 public static String makeGETRequest(String endpoint, String encodedBody) { String responseJSON = null; URL url; HttpURLConnection connection; t

请不要将我的问题与使用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;
}
发生的情况是,根据连接.getInputStream()连接.getOutPutStream()。

调用connection.getOutPutStream()时,即使使用connection.setRequestMethod(“GET”)将请求类型显式设置为GET,请求类型也会自动设置为POST

问题是我使用的是第三方Web服务(API),它接受请求参数作为GET请求的主体

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

<response>
{json}

/Myapi端点
body=参数1=作为应用程序的值/x-www-form-urlencoded
{json}

我很清楚,大多数情况下GET没有请求主体,但许多web服务经常使用GET请求,并将参数作为主体,而不是查询字符串。请指导我如何在不使用任何第三方库(OkHttp、改型、Glide等)的情况下在android中使用body发送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);
    }
}
package com.kundan.test;
导入java.io.BufferedReader;
导入java.io.InputStreamReader;
导入java.io.OutputStream;
导入java.net.Socket;
公共类GetWithBody{
公共静态最终字符串TYPE=“GET”;
公共静态最终字符串HTTP_VERSION=“HTTP/1.1”;
公共静态最终字符串行\u END=“\r\n”;
公共静态void main(字符串[]args)引发异常{
Socket Socket=new Socket(“localhost”,8080);//主机名和端口默认值为80
OutputStream OutputStream=socket.getOutputStream();
outputStream.write((TYPE+“”+HTTP_VERSION+LINE_END).getBytes());//
write(((“用户代理:Java套接字”+LINE_END).getBytes());
write(((“内容类型:application/x-www-form-urlencoded”+LINE_END).getBytes());
outputStream.write(第_-END.getBytes()行);//头的结尾
outputStream.write(((((“parameter1=value¶meter2=value2”+LINE_END).getBytes());//正文
outputStream.flush();
BufferedReader BufferedReader=新的BufferedReader(新的InputStreamReader(socket.getInputStream());
StringBuilder=新的StringBuilder();
字符串读取=null;
而((read=bufferedReader.readLine())!=null){
builder.append(读取);
}
字符串结果=builder.toString();
系统输出打印项次(结果);
}
}
这是原始HTTP请求转储

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

parameter1=value&parameter2=value2
获取HTTP/1.1
用户代理:Java套接字
内容类型:application/x-www-form-urlencoded
参数1=值&参数2=值2

注意:这是针对http请求的。如果您想要https连接,请参考链接,可能是因为。我不确定是否有图书馆支持这一点。您需要打开自己的套接字连接并手动与服务器通信。这可能不太令人愉快。对于那些阅读此问题并愿意使用库的人来说,尽管您可能能够使用Apache HttpClient库的独立打包(请参阅)。请使用librariesHTTP GET with body不受支持,原因是它是幂等的,这意味着多次调用这个方法不会有任何副作用。所以请不要违背标准。使用支持请求主体的方法。