android - 如何修改我的代码,以便可以将正文参数添加到发布请求
问题描述
我有一个项目,其中有一些 url,每个都指向一个端点。我已经通过带有 JSON 的 post 请求连接到这些端点,我必须在其中插入一个参数(即:“email”:“mail@etc.com”),以便获得一个我将放入正文的令牌我要连接的端点的下一个请求。
我尝试使用 addRequestProperty() 和 setRequestProperty() ,但我不知道出了什么问题。在日志中,我在尝试发出 http 请求时出现内部服务器错误(代码 500)。
我有一个端点,我不必向其传递任何参数并且工作正常,提供一个“东西”列表,每个端点的 JSON 结果中都有一个 id。然后我必须获取每个 id,所以当我从屏幕上的列表中单击“东西”时,另一个端点被称为在另一个活动中为我提供该“东西”详细信息的结果 - 对于这个端点,我需要传递任何项目我单击从早期 JSON 结果中获取的特定 ID。
私有静态字符串 makeHttpRequestGetUser(URL url) 抛出 IOException {
String jsonResponse = "";
if(url == null)
return jsonResponse;
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
//urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.addRequestProperty("email", "t1@gmail.com");
urlConnection.setRequestMethod("POST");
urlConnection.connect();
if(urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {
Log.e(TAG, "Error response code in GetUser request: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
Log.e(TAG, "Problem retrieving the "stuff" JSON result.", e);
} finally {
if(urlConnection != null)
urlConnection.disconnect();
if(inputStream != null)
inputStream.close();
}
return jsonResponse;
}
私有静态字符串 extractTokenFromJson(String spotJSON) {
if(TextUtils.isEmpty(spotJSON))
return null;
String tokenValue = "";
try {
JSONObject baseJsonResponse = new JSONObject(spotJSON);
JSONObject result = baseJsonResponse.getJSONObject("result");
tokenValue = result.getString("token");
} catch (JSONException e) {
Log.e(TAG, "Problem parsing the token", e);
}
return tokenValue;
}
解决方案
首先,为什么您不使用 Volley(由 google 推荐)库与您的其余 API 进行通信?如果您决定将其更改为 volley,请从此处开始: Android 的 Volley Library并使用我在VolleyWebClient之前编写的一个小类使其更容易,您只需将其添加到您的项目中并享受。
但是为了您自己的代码,我认为响应中的 500 错误表明您的请求的内容类型丢失。通常要获取令牌,您可以像这样使用表单内容类型:
setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
我希望它能帮助你并拯救你的一天。
推荐阅读
- arrays - DI序列的排列排序
- wordpress - 无法获取带有特定“product_cat”的帖子。WP_Query 为空
- javascript - 尝试模拟滚动时使用 +/- 值调用 onpointermove
- android - Volley HttpHeaderParser.parseDateAsEpoch:无法解析 dateStr:-1,回退到 0
- javascript - MomentJS 在分配给新变量时更改值
- python - python中列表的招摇验证错误
- sql - 是否有模仿 nvl() 的 Python fn 或者我可以使用 SQL 来做到这一点?
- biztalk - BizTalk-2016 Feature Pack 3 在累积更新 6 之后安装
- php - Laravel - 检查集合是否有关系
- python - virtualenv 安装包(先激活虚拟环境)与 pipenv 安装包(稍后激活虚拟环境)?