作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用以下代码连接到 .Net Web API
,但据我了解,我使用的是 POST
方法,因为我正在使用 HttpPost
对象,但 api 说:
The requested resource does not support http method 'GET'.
我的代码:
private boolean POST(List<NameValuePair>[] nvPair) {
HttpClient httpclient = new DefaultHttpClient();
String UrlString = URLEncodedUtils.format(nvPair[0], "utf-8");
HttpPost httppost = new HttpPost(apiBaseUri + UrlString);
try {
httppost.setEntity(new UrlEncodedFormEntity(nvPair[0]));
HttpResponse response = httpclient.execute(httppost);
String respond = response.getStatusLine().getReasonPhrase();
Log.d("MSG 3 > ", respond);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return true;
}
最佳答案
用于发送 HTTP Post 请求
String UrlString = URLEncodedUtils.format(nvPair[0], "utf-8");
URL url = new URL(apiBaseUri + UrlString);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestProperty("User-Agent", "android");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestMethod("POST");
connection.setDoInput(true);
int responseCode = connection.getResponseCode();
String response = readResponse(connection);
关于java - 如何向 api 发出 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19622720/
我是一名优秀的程序员,十分优秀!