gpt4 book ai didi

java - Android GET 和 POST 请求

转载 作者:行者123 更新时间:2023-12-01 23:54:56 25 4
gpt4 key购买 nike

任何人都可以向我指出发送 GET 和 POST 请求的方法的良好实现吗?他们有很多方法可以做到这些,我正在寻找最好的实现。其次,是否有一种通用的方式来发送这两种方法,而不是使用两种不同的方式。毕竟 GET 方法仅在查询字符串中包含参数,而 POST 方法使用参数的 header 。

谢谢。

最佳答案

您可以使用HttpURLConnection 类(在java.net 中)发送POST 或GET HTTP 请求。它与可能想要发送 HTTP 请求的任何其他应用程序相同。发送 Http 请求的代码如下所示:

import java.net.*;
import java.io.*;
public class SendPostRequest {
public static void main(String[] args) throws MalformedURLException, IOException {
URL reqURL = new URL("http://www.stackoverflow.com/"); //the URL we will send the request to
HttpURLConnection request = (HttpURLConnection) (reqUrl.openConnection());
String post = "this will be the post data that you will send"
request.setDoOutput(true);
request.addRequestProperty("Content-Length", Integer.toString(post.length)); //add the content length of the post data
request.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //add the content type of the request, most post data is of this type
request.setMethod("POST");
request.connect();
OutputStreamWriter writer = new OutputStreamWriter(request.getOutputStream()); //we will write our request data here
writer.write(post);
writer.flush();
}
}

GET 请求看起来有点不同,但大部分代码是相同的。您不必担心使用流进行输出或指定内容长度或内容类型:

import java.net.*;
import java.io.*;

public class SendPostRequest {
public static void main(String[] args) throws MalformedURLException, IOException {
URL reqURL = new URL("http://www.stackoverflow.com/"); //the URL we will send the request to
HttpURLConnection request = (HttpURLConnection) (reqUrl.openConnection());
request.setMethod("GET");
request.connect();

}
}

关于java - Android GET 和 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11939362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com