这是我通常用来向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()
构造函数没有参数,所以该怎么办?
答案 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();
}