问题描述
我有一个节点后端,该后端在登录后返回用户的id, email and JWT token
.在 JSON响应正文中设置ID和电子邮件,并将令牌设置为HTTP标头.
I have a node backend, which returns the id, email and JWT token
of an user after login. Id and email are set in the JSON response body and the token is set as a HTTP header.
我想做的只是从标题中读取该令牌,并将其存储以供将来请求,直到用户注销为止,因为我随后将删除该令牌.
What I want to do is just read that token from the header and store it for future requests until the user logs out, since I am deleting the token afterwards.
我发现了几篇有关如何通过覆盖getHeaders()
设置标题以及如何通过覆盖parseNetworkResponse()
读取标题的帖子.我对parseNetworkResponse()
的问题是,我必须将信息写在JSON主体上,这是我想避免的. getHeaders()
的另一个问题是我无法将标头硬编码"到HashMap中,因为我必须使用从服务器生成的JWT token
.
I found several posts about how to set the header by overriding getHeaders()
and how to read the header by overriding parseNetworkResponse()
. My problem with parseNetworkResponse()
is, that I would have to write the information on the JSON body, which I want to avoid. My other problem with getHeaders()
is that I can't "hardcode" my header into the HashMap, because I have to use the JWT token
generated from the server.
这是我的第一个Android项目,总的来说,我认为这是一个简单的用例,但在这一点上我感到有些困惑,因此我们将不胜感激.
This is my first Android project and overall I believe it's a simple use case but I am confused a bit at this point, so any help would be much appreciated.
相关代码:
// AuthenticationRequest.java
public class AuthenticationRequest extends JsonObjectRequest{
public AuthenticationRequest(int method, String url, JSONObject payload,
Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(method, url, payload, listener, errorListener);
}
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
JSONObject jsonResponse = new JSONObject(jsonString);
// I could fetch here with response.headers
return Response.success(jsonResponse, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException | JSONException e) {
return Response.error(new ParseError(e));
}
}
}
// BasicActivity.java
private void sendRequestToServer(String url, int method, JSONObject payload, final Class toGo) {
final AuthenticationRequest request =
new AuthenticationRequest(method, url, payload, response -> {
try {
startActivity(new Intent(this, toGo).putExtra("jsonData", response.toString()));
} catch (Exception e) {
e.printStackTrace();
}
}, Throwable::printStackTrace);
VolleySingleton.getInstance(this).addToRequestQueue(request);
}
推荐答案
因此,经过一番尝试后,我解决了我的问题.我创建了一个TokenHandler
类,它确实很基础,只关心设置/获取以及以后删除令牌的事情.
So after playing around a bit I solved my issue. I created a TokenHandler
class which is really basic and just cares about setting/getting and later deleting a token.
TokenHandler.java
public final class TokenHandler {
private TokenHandler() {}
private static String token = "";
public static void setToken(String newToken) {
if (newToken != null)
token = newToken;
}
public static String getToken() {
return token;
}
}
您可以像这样在子类的请求中进行设置:
And you set it up on your sub-classed Request like this:
AuthRequest.java
public class AuthRequest extends JsonObjectRequest{
// constructor
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
JSONObject jsonResponse = new JSONObject(jsonString);
// set token after receiving from login response
TokenHandler.setToken(response.headers.get("x-auth"));
return Response.success(jsonResponse, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException | JSONException e) {
return Response.error(new ParseError(e));
}
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("x-auth", TokenHandler.getToken());
return headers;
}
}
这篇关于Android Volley读取并存储HTTP标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!