如何在没有任何参数的情况下在Java / Android中发送POST请求?

时间:2014-11-27 23:05:22

标签: 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但没有params 所以,如果我将NULL作为参数传递,我会得到一个空指针异常,并且没有新的UrlEncodedFormEntity()构造函数没有参数,所以该怎么办?

1 个答案:

答案 0 :(得分:2)

如果您没有要在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();
}