Volley POST 请求 Android 令牌
Volley POST request Android token
我是新 android 编程的新手,目前正在使用 Volley POST 请求库来创建登录页面。我已经有一个可以工作的 API,它会在您发出 post 请求时提供一个字符串标记。现在我已经对用户名和密码进行了硬编码,只是为了通过创建 Toast 来查看 post 请求是否有效。但是,当我单击提交按钮时,它会在 toast 中打印出 200,这没有意义,因为令牌非常大。吐司出现需要几秒钟。这是 API 给出的(我需要令牌):
{
"status": true,
"result": {
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjI4OTkiLCJvdGhlciI6eyJ1c2VyX2lkIjoiMjg5OSIsImRvbWFpbl9saXN0X2ZrIjoiMSIsInV1aWQiOiIxNTY4NzA2Mjg4ODk5IiwidXNlcl90eXBlIjoiNCIsInJlZ190eXBlIjoiMSIsImVtYWlsIjoiZmFpc2FsY2t5ZkBnbWFpbC5jb20iLCJwYXNzd29yZCI6ImY0NjY4Mjg4ZmRiZjk3NzNkZDk3NzlkNDEyOTQyOTA1Iiwic3RhdHVzIjoiMSIsImRhdGVfb2ZfYmlydGgiOm51bGwsImltYWdlIjpudWxsLCJ0aXRsZSI6bnVsbCwiYWdlbmN5X25hbWUiOm51bGwsImFnZW50X25hbWUiOm51bGwsImFnZW5jeV9lbWFpbCI6IiIsImZpcnN0X25hbWUiOiJGYWlzYWwiLCJtaWRkbGVfbmFtZSI6IiIsImxhc3RfbmFtZSI6bnVsbCwiYWRkcmVzcyI6IjMxIEQiLCJjaXR5IjoiUmFzaGlkaXlhIiwic3RhdGUiOiJEdWJhaSIsImNvdW50cnlfY29kZSI6IjIxMiIsImNvdW50cnlfbmFtZSI6IlVuaXRlZCBBcmFiIEVtaXJhdGVzIiwicGhvbmUiOiIwNTY2OTkzNzA5IiwicGhvbmVfY29kZSI6Iis5NzEiLCJvZmZpY2VfcGhvbmUiOm51bGwsInBpbl9jb2RlIjoiMTE0MTYwIiwicGFuX251bWJlciI6bnVsbCwicGFzc3BvcnRfbnVtYmVyIjoiIiwiY291bnRyeV9pc3N1ZSI6IjAiLCJwYXNzX2V4cGlyZV9kYXRlIjoiMDAwMC0wMC0wMCIsImNyZWF0aW9uX3NvdXJjZSI6InBvcnRhbCIsImNyZWF0ZWRfZGF0ZXRpbWUiOiIyMDE5LTA5LTE3IDA3OjQ0OjQ4IiwiY3JlYXRlZF9ieV9pZCI6IjAiLCJsYW5ndWFnZV9wcmVmZXJlbmNlIjoiZW5nbGlzaCIsInNpZ25hdHVyZSI6bnVsbCwic3ViX2FkbWluX3ByZXZpbGFnZSI6bnVsbCwicHJvbW9fY29kZSI6bnVsbCwiaG90ZWxfcHJvbW9fY29kZSI6bnVsbCwiY2FyX3Byb21vX2NvZGUiOm51bGwsImdyb3VwIjoiMCJ9LCJBUElfVElNRSI6MTU3MjQwMzU2Nn0.rU3NIqiHxsgOS7zeeuSCmPZP9Sc7RMXVGKWXni4JBLM"
}
}
这是我的当前代码:
public class Login extends AppCompatActivity {
EditText username, password;
Button loginButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
this.username = findViewById(R.id.editTextUsername);
this.password = findViewById(R.id.editTextPassword);
this.loginButton = findViewById(R.id.buttonLogin);
this.loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Toast.makeText(Login.this, "I just clicked the button",
Toast.LENGTH_LONG).show();
RequestQueue requestQueue =
Volley.newRequestQueue(getApplicationContext());
String URL =
"http://apidev.travelhouse.world/api/v1/user/login?
username=faisalckyf@gmail.com&password=faisal";
final JSONObject jsonBody = new JSONObject();
// jsonBody.put("username", "faisalckyf@gmail.com");
// jsonBody.put("password", "faisal");
final String requestBody = jsonBody.toString();
JsonArrayRequest jsonObjectRequest = new
JsonArrayRequest(Request.Method.POST, URL, new
Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
String token = "";
for (int i = 0; i < response.length(); i++)
{
try {
JSONObject hit =
response.getJSONObject(i);
token = hit.getString("token");
} catch (JSONException e) {
e.printStackTrace();
}
}
Toast.makeText(Login.this, token,
Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Login.this, error.toString(),
Toast.LENGTH_LONG).show();
}
}) {
@Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
@Override
public byte[] getBody() {
try {
return requestBody == null ? null :
requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while
trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
@Override
protected Response<String>
parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString =
String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(response,
HttpHeaderParser.parseCacheHeaders(response));
}
@Override
public Map getHeaders() throws AuthFailureError {
HashMap headers = new HashMap();
headers.put("Content-Type", "application/json");
headers.put("X-API-KEY", "CODEX@123");
return headers;
}
};
requestQueue.add(jsonObjectRequest);
}
//
});
//
}
}
您正在 parseNetworkResponse()
函数中解析状态代码而不是结果标记:
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
您需要将 return 语句更改为:
return Response.success(response, HttpHeaderParser.parseCacheHeaders(response));
如您所见,在您的函数中您正在获取响应,但您只是将状态代码 (responseString
) 传递给结果。
其次,您的回复实际上是 JSON 对象。您需要将其解析为 JsonObject(或使用 JsonObjectRequest),然后读取嵌套在 result
.
中的值 token
我是新 android 编程的新手,目前正在使用 Volley POST 请求库来创建登录页面。我已经有一个可以工作的 API,它会在您发出 post 请求时提供一个字符串标记。现在我已经对用户名和密码进行了硬编码,只是为了通过创建 Toast 来查看 post 请求是否有效。但是,当我单击提交按钮时,它会在 toast 中打印出 200,这没有意义,因为令牌非常大。吐司出现需要几秒钟。这是 API 给出的(我需要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lbmNlIjoiZW5nbGlzaCIsInNpZ25hdHVyZSI6bnVsbCwic3ViX2FkbWluX3ByZXZpbGFnZSI6bnVsbCwicHJvbW9fY29kZSI6bnVsbCwiaG90ZWxfcHJvbW9fY29kZSI6bnVsbCwiY2FyX3Byb21vX2NvZGUiOm51bGwsImdyb3VwIjoiMCJ9LCJBUElfVElNRSI6MTU3MjQwMzU2Nn0.rU3NIqiHxsgOS7zeeuSCmPZP9Sc7RMXVGKWXni4JBLM"
}
}
这是我的当前代码:
public class Login extends AppCompatActivity {
EditText username, password;
Button loginButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
this.username = findViewById(R.id.editTextUsername);
this.password = findViewById(R.id.editTextPassword);
this.loginButton = findViewById(R.id.buttonLogin);
this.loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Toast.makeText(Login.this, "I just clicked the button",
Toast.LENGTH_LONG).show();
RequestQueue requestQueue =
Volley.newRequestQueue(getApplicationContext());
String URL =
"http://apidev.travelhouse.world/api/v1/user/login?
username=faisalckyf@gmail.com&password=faisal";
final JSONObject jsonBody = new JSONObject();
// jsonBody.put("username", "faisalckyf@gmail.com");
// jsonBody.put("password", "faisal");
final String requestBody = jsonBody.toString();
JsonArrayRequest jsonObjectRequest = new
JsonArrayRequest(Request.Method.POST, URL, new
Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
String token = "";
for (int i = 0; i < response.length(); i++)
{
try {
JSONObject hit =
response.getJSONObject(i);
token = hit.getString("token");
} catch (JSONException e) {
e.printStackTrace();
}
}
Toast.makeText(Login.this, token,
Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Login.this, error.toString(),
Toast.LENGTH_LONG).show();
}
}) {
@Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
@Override
public byte[] getBody() {
try {
return requestBody == null ? null :
requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while
trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
@Override
protected Response<String>
parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString =
String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(response,
HttpHeaderParser.parseCacheHeaders(response));
}
@Override
public Map getHeaders() throws AuthFailureError {
HashMap headers = new HashMap();
headers.put("Content-Type", "application/json");
headers.put("X-API-KEY", "CODEX@123");
return headers;
}
};
requestQueue.add(jsonObjectRequest);
}
//
});
//
}
}
您正在 parseNetworkResponse()
函数中解析状态代码而不是结果标记:
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
您需要将 return 语句更改为:
return Response.success(response, HttpHeaderParser.parseCacheHeaders(response));
如您所见,在您的函数中您正在获取响应,但您只是将状态代码 (responseString
) 传递给结果。
其次,您的回复实际上是 JSON 对象。您需要将其解析为 JsonObject(或使用 JsonObjectRequest),然后读取嵌套在 result
.
token