作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是我通常用来向 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/
我是一名优秀的程序员,十分优秀!