我正在使用 Twilio Rest API 使用 android studio 发送无线命令。我已经根据他们的无线命令文档实现了代码结构。但是当我点击按钮获得响应时,我得到的是未经授权的 401 响应,而不是得到想要的结果。我是第一次使用他们的 API,所以显然不知道我在这里做错了什么。
这是我的代码:
public void byApi() {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(ApiRetro.BASE_URL)
.build();
这里 SIMSID 是 twilio sim 卡的唯一名称,我发送的命令是 hello machine! 凭证凭证=新凭证(SIMSID,COMMAND);
ApiRetro apiRetro = retrofit.create(ApiRetro.class);
Call<ResponseBody> call = apiRetro.getSid(credentials);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if(response.isSuccessful())
{
try {
String hyyy=response.body().string();
try {
JSONObject jsonObject=new JSONObject(hyyy);
String test=jsonObject.getString("status");
Log.v("sdfg",test);
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
Log.v("TAG",response.body().string());
Toast.makeText(getApplicationContext(),response.body().string(),Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
else
{
Toast.makeText(getApplicationContext(),response.code()+" "+response.message(),Toast.LENGTH_LONG).show();
Log.v("one", String.valueOf(response.errorBody()));
Log.v("two",response.message());
Log.v("three", String.valueOf(response.code()));
Log.v("four", String.valueOf(response.headers()));
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.getStackTrace();
}
});
}
Retrofit 请求的界面如下所示:
String BASE_URL = "https://wireless.twilio.com/v1/";
@Headers({"AccountSid:yyyyyyyyyyyyyyyyyxxxx",
"AuthToken: yyyyyyyyyyyyyyyyyyyyxxx",
"token: ",
"Content-Type: application/x-www-form-urlencoded"})
@POST("Commands")
Call<ResponseBody> getSid(@Body Credentials credentials);
体类:
public class Credentials {
String Sim;
String Command;
public Credentials(String sim, String command) {
Sim = sim;
Command = command;
}
public String getSim() {
return Sim;
}
public void setSim(String sim) {
Sim = sim;
}
public String getCommand() {
return Command;
}
public void setCommand(String command) {
Command = command;
}
}