我正在尝试通过Json从在线API获取一些数据,但是由于以前从未做过,所以无法弄清楚身份验证的工作原理。 它不是用户密码对,而是基于唯一密钥。 卷毛看起来像这样:
curl -X GET --header'Accept:application / json'--header“ authorization:Bearer [ unique key ]”'URL to Json Object'
没有做太多尝试,因为我是在Java中实现json的新手。该列表未加载,并且正在logcat中获取以下内容:
E / Volley:[31231] BasicNetwork.performRequest:URL的意外响应代码403
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private PlayerListAdapter mAdapter;
private ArrayList<PlayerListItem> mPlayerList;
private RequestQueue mRequestQueue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.playerList);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mPlayerList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJson();
}
private void parseJson() {
String url = getString(R.string.url_to_members);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("items");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject players = jsonArray.getJSONObject(i);
String playerName = players.getString("name");
String playerRole = players.getString("role");
int playerTrophies = players.getInt("trophies");
int playerDonations = players.getInt("donations");
mPlayerList.add(new PlayerListItem(playerName, playerRole, playerTrophies, playerDonations));
}
mAdapter = new PlayerListAdapter(MainActivity.this, mPlayerList);
mRecyclerView.setAdapter(mAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
String apiToken = "Bearer" + Base64.encodeToString(getString(R.string.api_key).getBytes(), Base64.NO_WRAP);
headers.put("Accept:", "application/json");
headers.put("authorization:", "Bearer " + apiToken);
return headers;
}
};
mRequestQueue.add(request);
}
}