[英]How can I modify my code so I can add a body parameter to the post request
我有一个项目,其中我有一些网址,每个网址都通向一个端点。 我通过带有JSON的帖子请求连接到这些端点,我必须在其中插入一个参数(即:“email”:“mail@etc.com”),以便获得一个我将放入体内的令牌我要连接的端点的下一个请求。
我尝试使用addRequestProperty()和setRequestProperty(),我无法弄清楚是什么问题。 在日志中,似乎在尝试发出http请求时出现内部服务器错误(代码500)。
我有一个端点,我不需要传递任何参数,并且工作正常,提供一个“东西”列表,每个都有一个来自端点的JSON结果的id。 然后我必须接受每个id,所以当我点击屏幕上列表中的“东西”时,另一个端点被调用,在另一个活动中提供带有“stuff”详细信息的结果 - 对于这个端点我需要传递给任何item我单击从早期JSON结果中获取的特定id。
private static String makeHttpRequestGetUser(URL url)throws 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 Library,使用VolleyWebClient之前编写的小类更轻松,您只需将其添加到项目中即可享受。
但是为了您自己的代码,我认为响应中的500错误显示您的请求的内容类型丢失。 通常获取令牌你可以使用表格内容类型如下:
setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
我希望它能帮助你,拯救你的一天。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.