THE CODE IN BELOW IS THE SOLUTION
我正在尝试将具有多个元素的json对象发送到社交媒体应用程序以获取令牌(我需要提供用户名/密码)并获取令牌。我搜遍了所有的SO并找到了一些与此相似的问题并尝试实现它们但是每个问题最终都会出现错误请求(意思不是预期的json)这是我对此问题的最后一次尝试。我知道它应该返回状态代码200,因为我在休息高级客户端中尝试了它。 Sending a JSON HTTP POST request from Android
以下是我尝试过各种不同方式的代码。
HttpURLConnection urlConnection=null;
try {
URL url = new URL(http);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type","application/json");
urlConnection.setRequestProperty("user-agent","Agent/1");
urlConnection.connect();
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("username", mJidView.getText().toString());
jsonParam.put("password",mJidView.getText().toString());
OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
out.write(jsonParam.toString());
out.close();
int HttpResult =urlConnection.getResponseCode();
if(HttpResult ==HttpURLConnection.HTTP_OK){
BufferedReader br = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream(),"utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
System.out.println(""+sb.toString());
}else{
System.out.println(urlConnection.getResponseMessage());
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(urlConnection!=null)
urlConnection.disconnect();
}
注意:应用程序需要用户代理的标头,其签名位于此处。
- Request body:
{"username": "test", "password": "12345"}