我正在尝试将我的应用转换为使用WebAPI和令牌身份验证。我也正在离开Apache http并使用凌空。
下面我有一个名为NetworkManager的类来处理凌空请求。 在我的主Activity中有一个登录按钮,它从networkManager类调用getAuthenicationTokens方法。我使用了customeListener将响应转发回调用Activity。
CustomListener:
public interface CustomListener<T>
{
public void getResult(T object);
}
的活动:
buttonLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
NetworkManager.getInstance().getAuthenticationTokens(null, new CustomListener<JSONObject>()
{
@Override
public void getResult(JSONObject result)
{
Log.e(TAG, "Json object length = " + result.length());
}
});
NetworkManager中的方法:
public void getAuthenticationTokens(Object param1, final CustomListener<JSONObject> listener)
{
//String url = prefixURL + "this/request/suffix";
String url = "https://lw.xxx.co.uk/connect/token";
Map<String, Object> jsonParams = new HashMap<>();
jsonParams.put("scope", "openid email phone profile offline_access roles");
jsonParams.put("resource", "window.location.origin");
jsonParams.put("grant_type", "password");
jsonParams.put("username", "support@xxx.com");
jsonParams.put("password", "tempPxxx");
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(jsonParams),
new Response.Listener<JSONObject>()
{
@Override
public void onResponse(JSONObject response)
{
Log.d(TAG + ": ", "somePostRequest Response : " + response.toString());
if(null != response.toString())
listener.getResult(response);
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error)
{
if (null != error.networkResponse)
{
Log.d(TAG + ": ", "Error Response code: " + error.networkResponse.statusCode);
listener.getResult(null);
}
}
}){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = super.getHeaders();
if(params==null)params = new HashMap<>();
params.put("Content-Type","application/x-www-form-urlencoded");
//..add other headers
return params;
}
};
requestQueue.add(request);
}
我尝试使用以下帖子(通过Subhash回答)为请求添加标题,但是我添加标题时出现以下异常。
例外:
NetworkDispatcher.run: Unhandled exception java.lang.UnsupportedOperationException
java.lang.UnsupportedOperationException
at java.util.AbstractMap.put(AbstractMap.java:203)
at loneworker.carefreegroup.com.loneworker.NetworkManager$3.getHeaders(NetworkManager.java:100)
at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:93)
at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:96)
at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:112)
有没有人知道添加标题的问题是什么。 例外是第100行,这里是
params.put("Content-Type","application/x-www-form-urlencoded");
答案 0 :(得分:1)
你试过了吗?
Map<String, String> params = new HashMap<>(super.getHeaders());
我测试了它,它对我有用。