我需要使用以下JSON对象格式向服务器发送POST请求:
{"auth": {"tenantName": "<tenant>", "passwordCredentials": {"username": "<user>", "password": "<password>"}}}
获取身份验证令牌作为后续请求的响应:
{
access: {
token: {
issued_at: "2014-11-03T01:45:53.819103"
expires: "2014-11-03T02:45:53Z"
id: "686889ba4244432696aaac1d022f4973"
到目前为止,我只是用排球来测试连接,看看我是否能在Toast中得到正确的响应:
public void loginRequest(){
String[] credentials = getSharedPrefs();
final String user = credentials[0];
final String pass = credentials[1];
final String url = credentials[2];
JSONObject login = new JSONObject();
JSONObject result = new JSONObject();
try {
JSONObject auth = login.getJSONObject("auth");
JSONObject tenantName = auth.getJSONObject("tenantName");
JSONObject passwordCredentials = auth.getJSONObject("passwordCredentials");
JSONObject username = passwordCredentials.getJSONObject("username");
JSONObject password = passwordCredentials.getJSONObject("password");
login.put("tenantName","");
login.put("username",user);
login.put("password",pass);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.POST, url, login,
new Response.Listener<JSONObject>()
{
@Override
public void onResponse(JSONObject response) {
// display response
// TO DO
Toast toast = Toast.makeText(Login.this,response.toString(),Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL,0,120);
toast.show();
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Login.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
}
){
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("tenantName", "");
params.put("username", user);
params.put("password", pass);
return params;
}
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Accept", "application/json");
params.put("Content-Type", "application/json");
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(getRequest);
}
}
但是我收到以下错误:
E/Volley﹕ [893] NetworkDispatcher.run: Unhandled exception java.lang.RuntimeException: Bad URL
java.lang.RuntimeException: Bad URL
at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:147)
at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:110)
Caused by: java.net.MalformedURLException: Protocol not found:
at java.net.URL.<init>(URL.java:176)
at java.net.URL.<init>(URL.java:125)
at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:101)
at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:96)
at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:110)
知道我错过了什么吗?
编辑:我做了一些挖掘,并意识到上面的错误是由字符串&#34; url&#34;上的错误getter引起的。我修好了,但现在我明白了:
E/Volley﹕ [787] BasicNetwork.performRequest: Unexpected response code 400 for http://10.10.10.10:5000/v2.0/tokens
似乎代码没有正确发送JSON。例如,如果我尝试使用Advanced Rest Client向网站发送除aplication / json之外的任何内容,我还会收到 400 Bad Request
答案 0 :(得分:0)
package com.example.wexindemo;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
public class JsonObjectPostRequest extends Request<JSONObject> {
private Map<String, String> mMap;
private String params;
private Listener<JSONObject> mListener;
public JsonObjectPostRequest(String url, Listener<JSONObject> listener,
ErrorListener errorListener, String params) {
super(Request.Method.POST, url, errorListener);
mListener = listener;
this.params = params;
}
public JsonObjectPostRequest(String url, Listener<JSONObject> listener,
ErrorListener errorListener, Map map) {
super(Request.Method.POST, url, errorListener);
mListener = listener;
mMap = map;
}
// @Override
// protected Map<String, String> getParams() throws AuthFailureError {
//
// return mMap;
//
// }
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Charset", "UTF-8");
headers.put("Content-Type", "application/x-javascript");
headers.put("Accept-Encoding", "gzip,deflate");
return headers;
}
@Override
public byte[] getBody() throws AuthFailureError {
return params == null ? super.getBody() : params.getBytes();
}
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString =
new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
@Override
protected void deliverResponse(JSONObject response) {
mListener.onResponse(response);
}
}
ps:You try to use this class to send a post request
答案 1 :(得分:0)
我使用String:
使其工作 final String json = "{\"auth\": {\"tenantName\": \""+tnt+"\", \"passwordCredentials\": {\"username\": \""+user+"\", \"password\": \""+pass+"\"}}}";
JSONObject login = null;
try {
login = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
但是我仍然想知道如何使用JSONObject以编程方式来了解正确的语法。任何人?