如何修改我的代码,以便可以将正文参数添加到发布请求
Posted
技术标签:
【中文标题】如何修改我的代码,以便可以将正文参数添加到发布请求【英文标题】:How can I modify my code so I can add a body parameter to the post request 【发布时间】:2019-09-12 02:48:10 【问题描述】:我有一个项目,其中有一些 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;
【问题讨论】:
【参考方案1】:首先,您为什么不使用 Volley(由 google 推荐)库与您的其余 API 进行通信? 如果您决定将其更改为 volley,请从此处开始: Volley Library for android 并通过我之前写的一个小课程使其更容易VolleyWebClient 您只需将其添加到您的项目中即可享受。
但为了您自己的代码,我认为响应中的 500 错误表明您的请求的内容类型缺失。通常要获取令牌,您可以像这样使用表单内容类型:
setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
我希望它能帮助你并拯救你的一天。
【讨论】:
嘿,拉瓦伊!感谢您抽出宝贵时间回答!我会看一下 Volley 库,如果它更简单,我会尝试更改它。另外,感谢您对我的代码的反馈!以上是关于如何修改我的代码,以便可以将正文参数添加到发布请求的主要内容,如果未能解决你的问题,请参考以下文章