我正在尝试使用API_KEY从在我的Google开发者控制台项目中注册的信标中获取附件。如Proximity Beacon API中所述,可以通过仅使用API密钥并在POST请求中发送正文来进行请求。 我已经完成了下面显示的所有操作。 1)发出http请求的方法:
public String getAttachments(String beaconname, String account,String data) {
//beacon name = beacons/3!....
//acountname = emailused;
//data = json body
String token = null;
String SCOPE = "oauth2:https://www.googleapis.com/auth/userlocation.beacon.registry";
String result = null;
try {
token = GoogleAuthUtil.getToken(getActivity(), account, SCOPE);
Log.w("Token", token);
} catch (IOException e) {
e.printStackTrace();
} catch (GoogleAuthException e) {
e.printStackTrace();
}
BufferedReader bufferedReader = null;
HttpURLConnection httpURLConnection = null;
try {
URL url = new URL("https://proximitybeacon.googleapis.com/v1beta1/beaconinfo:getforobserved?key="+API_KEY);
Log.w("URL", url.toString());
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
httpURLConnection.setRequestProperty("Accept","application/json");
httpURLConnection.setRequestProperty("Authorization", "Bearer " + token);
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(httpURLConnection.getOutputStream(),"UTF-8"));
writer.write(data);
writer.flush();
writer.close();
Log.w("data sent",data);
int resposnecode = httpURLConnection.getResponseCode();
String responsemessage = httpURLConnection.getResponseMessage();
Log.e("Response code", resposnecode + "");
Log.e("Response message",responsemessage);
bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),"UTF-8"));
String line = null;
StringBuilder builder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
}
result = builder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpURLConnection.disconnect();
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
我与此发布请求一起发送的正文(上述方法中使用的数据参数)为:
{ "observations":[
{
"advertisedId":{
"type":"EDDYSTONE",
"id":"vv8QICkg/0QBAwASb9z/Ug=="
},
"timestampMs":"2018-11-20T10:31:02.972000000Z"
}],"namespacedTypes":[
"true-bla-020202/Bye"]}
我收到错误请求,代码为400。信标在信标仪表板中具有两个附件,并具有POST正文中提到的名称空间。我从几天开始一直没有成功。