我正在尝试连接到Android应用中的Google端点,但是当我在模拟器或真实设备上运行该应用时,两者均无法正常工作,并且出现错误404。 所以我创建了实现连接asynctask的按钮:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void tellJoke(View view) {
EndpointsAsyncTask asyncTask = new EndpointsAsyncTask(this);
asyncTask.execute();
}
}
这是asynctask的类:
public class EndpointsAsyncTask extends AsyncTask<Void, Void, String> {
private static MyApi myApiService = null;
private Context mContext;
public EndpointsAsyncTask (Context context){
mContext = context;
}
@Override
protected String doInBackground(Void... params) {
if(myApiService == null) { // Only do this once
MyApi.Builder builder = new
MyApi.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// 10.0.2.2 is localhost's IP address in Android emulator
// turn off compression when running against local devappserver
.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
@Override public void initialize(AbstractGoogleClientRequest<?>
abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});
// end options for devappserver
myApiService = builder.build();
}
try {
return myApiService.jokes().execute().getData();
} catch (IOException e) {
return e.getMessage();
}
}
@Override
protected void onPostExecute(String result) {
Intent intent = new Intent(mContext, AndroidLibraryActivity.class);
intent.putExtra("jokes", result);
mContext.startActivity(intent);
}
}
并且在android库中,我收到了这样的结果:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_library);
TextView jokes;
jokes = findViewById(R.id.jokes);
Intent intent = getIntent();
String joke = intent.getStringExtra("jokes");
jokes.setText(joke);
}
这是我的终点:
@Api(
name = "myApi",
version = "v1",
namespace = @ApiNamespace(
ownerDomain = "backend.builditbigger.gradle.udacity.com",
ownerName = "backend.builditbigger.gradle.udacity.com",
packagePath = ""
)
)
public class MyEndpoint {
/** A simple endpoint method that takes a name and says Hi back */
@ApiMethod(name = "jokes")
public MyBean jokes(){
MyBean response = new MyBean();
Joker jokes = new Joker();
String jokesResult = jokes.getJoke();
response.setData(jokesResult);
return response;
}
我也阅读了许多解决方案,但没有任何帮助,顺便说一句,当我在真实设备上运行它时,我将rooturl更改为此链接:
但是它不起作用,因此如何使其至少在模拟器设备上起作用!