如何修改我的代码,以便我可以向 post 请求添加 body 参数



我有一个项目,其中我有一些网址,每个网址都指向一个端点。我已经通过带有 JSON 的 post 请求连接到这些端点,我必须在其中插入一个参数(即:"email":"mail@etc.com"),以便获得一个令牌,我将把该令牌放入我要连接的端点的下一个请求的正文中。

我尝试使用addRequestProperty()和setRequestProperty(),但我无法弄清楚出了什么问题。在日志中,我在尝试发出 http 请求时似乎收到内部服务器错误(代码 500)。

我有一个端点,我不必向其传递任何参数并且工作正常,提供了一个"东西"列表,每个东西在端点的 JSON 结果中都有一个 id。然后我必须获取每个 id,因此当我单击屏幕上列表中的"内容"时,另一个端点称为在另一个活动中为我提供带有该"东西"详细信息的结果 - 对于此端点,我需要为任何项目传递我单击其从早期 JSON 结果中获取的特定 id。

private static String 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;
}

private static String 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(谷歌推荐)库与你的休息 API 进行通信? 如果您决定将其更改为凌空抽射,请在此处开始: 适用于Android的Volley库,并通过我之前编写的小类VolleyWebClient使其更加容易,您只需将其添加到您的项目中即可享受。

但是为了您自己的代码,我认为响应中的 500 错误表明您的请求的内容类型丢失。 通常要获取令牌,您可以使用表单内容类型,如下所示:

setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

我希望它能帮助你并拯救你的一天。

相关内容

最新更新