android - 如何为 Android HttpURLConnection 实现 getResponseMessage() / getResponseCode
问题描述
我正在向 HTTP 服务器发出获取和发布请求。一切似乎都运行良好,但我需要从响应消息中获取状态代码。这是我的发帖请求
postToHttp(URL url) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
DataOutputStream dataOutputStream = null;
Log.i(TAG , "calling :: " + url.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("city", "NYC");
jsonObject.put("country", "USA");
Log.i(TAG, "JSON onj :: " + jsonObject.toString());
dataOutputStream = new DataOutputStream(urlConnection.getOutputStream());
dataOutputStream.writeBytes(jsonObject.toString());
} catch (JSONException e) {
e.printStackTrace();
}finally {
dataOutputStream.flush();
dataOutputStream.close();
}
//Need to check the post status?
}
解决方案
只需调用 urlConnection.getResponseCode()
推荐阅读
- python - 在 Python 中循环文件
- python - 提取 Python 数据帧列 - 系列与数据帧检索
- java - 当用户滑动到第一个片段时,我如何祝酒
- angular - 如何在 ag-grid v18 中禁用执行 AND/OR 逻辑的列过滤器
- emulation - 无法在模拟器中创建集合
- node.js - Heroku、NodeJs 和 React 问题:SCRIPT5007:无法获取未定义或空引用的属性“应用”
- excel - excel的vba代码进行搜索,替换不同列上的相应数据
- android - ScrollView 带走了 LinearLayout 约束
- json - solr 中的 delimited_payload_string 字段类型是什么
- javascript - 未捕获的类型错误:不是函数