【发布时间】:2020-03-13 14:06:38
【问题描述】:
我已经被这个问题困扰了一段时间。我想要的是连接到一个 api 而 curl url 是:
curl --header "授权:令牌 9ea49e1ccb828fd7736d981aa3b027571da9ae86" https://owlbot.info/api/v4/dictionary/owl -s | json_pp
我的老师告诉我 Volley 是在请求 Curl 时要走的路,所以我尝试实现一些代码来处理与 API 的连接,但有些地方并不正确。出于测试目的,我将 JSONObject 响应转换为字符串,因此可以将其设置为 textview 以查看是否可以在模拟器中获取某些内容,但没有任何反应。 然后我尝试使用 Postman,看看我是否可以通过输入 url 和授权标头从 api 获得响应,我可以做到这一点。
private void httpRequestWithVolley() {
String server_url = "https://owlbot.info/api/v4/dictionary/owl";
final String API_TOKEN = "9ea49e1ccb828fd7736d981aa3b027571da9ae86";
// Initialize a new RequestQueue instance
final RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.GET,
server_url,
null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// Process the JSON
try {
String json = response.toString();
textView.setText(json);
JSONArray jsonArray = response.getJSONArray("definitions");
// Loop through the array elements
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String definition = jsonObject.getString("definition");
String image = jsonObject.getString("image_url");
int picture = Integer.parseInt(image);
}
String word = response.getString("word");
String pronunciation = response.getString("pronunciation");
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}
) {
@Override
public byte[] getBody() {
return super.getBody();
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
// return super.getHeaders();
Map<String,String> map = new HashMap<>();
map.put("Authorization", "Token " + API_TOKEN);
return map;
}
};
requestQueue.add(jsonObjectRequest);
}
【问题讨论】:
标签: android json android-studio curl