我对使用android studio很陌生,在使用API时遇到了一些麻烦:https://developer.companieshouse.gov.uk/api/docs/search/companies/companysearch.html#here
我正在尝试发送JSON请求以在文本视图中显示,但是我需要使用授权密钥来进行发送,因此我很努力地发送GET请求。我意识到这可能是重复的帖子,但是我已经搜寻了几天以尝试实施解决方案,但尚未成功。下面是我的代码:
public class MainActivity extends AppCompatActivity {
private TextView txtResult;
private RequestQueue queue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
queue = Volley.newRequestQueue(this);
txtResult = findViewById(R.id.txtResult);
Button buttonParse = findViewById(R.id.btnSearch);
buttonParse.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
jsonParse();
}
});
}
private void jsonParse(){
String url = "https://api.companieshouse.gov.uk/search/companies?q=tesco&items_per_page=1000&start_index=0";
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 companies = jsonArray.getJSONObject(i);
String title = companies.getString("address_snippet");
txtResult.append(title);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
String credentials = "MY_KEY";
String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
HashMap<String, String> headers = new HashMap<>();
headers.put("Authorization", "Basic " + base64EncodedCredentials);
return headers;
}
};
queue.add(request);
}
}
JSON响应正文示例:
{
"kind": "search#companies",
"page_number": 1,
"start_index": 0,
"items": [
{
"address_snippet": "Tesco House, Shire Park, Kestrel Way, Welwyn Garden City, United Kingdom, AL7 1GA",
"address": {
"postal_code": "AL7 1GA",
"locality": "Welwyn Garden City",
"country": "United Kingdom",
"address_line_1": "Kestrel Way",
"premises": "Tesco House, Shire Park"
},
"company_type": "plc",
"company_status": "active",
"kind": "searchresults#company",
https://developer.companieshouse.gov.uk/api/docs/index/gettingStarted/apikey_authorisation.html
如果有帮助,上面的文档说明了如何发送API密钥(我似乎无法弄清楚)。目前,当单击按钮时,它什么也没做(我认为由于授权问题,不允许应用程序获取JSON),对此我将非常感谢!