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

标签 java android

这是我通常用来向 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/

相关文章:

java - 有没有办法使用 JMeter 测量服务器处理时间?

Java 用递归解决迷宫问题

java - 如何将一些字符串转换为类名?

android - 如何使用 Android cameraX 访问外部 USB 摄像头?

java - "onRadioButtonClicked"方法不适用于由 "onCreate"方法实现的单选按钮

Java - 选择在 Canvas 上绘制的内容

Java int 转换返回 0

java - 安卓软键盘大小

android - AdMob:缺少必需的 XML 属性 adUnitID

php - 从 RecursiveDirectoryIterator 中过滤目录