gpt4 book ai didi

java - 如何在Java/Android中发送没有任何参数的POST请求?

转载 作者:行者123 更新时间:2023-12-02 05:13:17 27 4
gpt4 key购买 nike

这是我通常用来向 API 发送 POST 请求的代码:

if (method == "POST") {
// request method is POST
// defaultHttpClient

HttpPost httpPost = new HttpPost(url);

httpPost.setEntity(new UrlEncodedFormEntity(params));


HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();

inputStream = httpEntity.getContent();
}

到目前为止一切顺利,但现在有一个新的 API 调用应该是 POST 但没有参数因此,如果我将 NULL 作为参数传递,则会出现空指针异常,并且没有不带参数的新 UrlEncodedFormEntity() 构造函数,那么我该怎么办?

最佳答案

如果您没有要在 POST 中发送的实体,请跳过添加实体的命令。

if (method == "POST") {
HttpPost httpPost = new HttpPost(url);
if (params != null)
httpPost.setEntity(new UrlEncodedFormEntity(params));
// else - just nothing

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();

inputStream = httpEntity.getContent();
}

关于java - 如何在Java/Android中发送没有任何参数的POST请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27179787/

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