我试图从我的Android应用程序向Yelp发送API请求。我从这里获得了用Java发送请求的示例代码https://github.com/Yelp/yelp-api/tree/master/v2/java
当我运行存储库中提供的脚本时,它工作正常,但是,当我将代码添加到我的Android应用程序时,我收到了错误。
这是我的Android应用代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
YelpAPI yelp = new YelpAPI(
getString(R.string.yelp_consumer_key),
getString(R.string.yelp_consumer_secret),
getString(R.string.yelp_token),
getString(R.string.yelp_token_secret));
String result = yelp.searchForBusinessesByLocation("bar", "San Jose, CA");
System.out.println(result);
}
和堆栈跟踪:
--------- beginning of crash
07-23 12:50:23.848 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: PID: 2328
java.lang.RuntimeException: Unable to start activity ComponentInfo{.MainActivity}: org.scribe.exceptions.OAuthConnectionException: There was a problem while creating a connection to the remote service.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144) ...
我在互联网上发现了类似的问题,我认为这是因为我无法使用主线程发送请求。如何使用单独的线程发送请求?
答案 0 :(得分:1)
如果您只想创建一个新线程,可以这样做:
new Thread(new Runnable() {
public void run() {
YelpAPI yelp = new YelpAPI(
getString(R.string.yelp_consumer_key),
getString(R.string.yelp_consumer_secret),
getString(R.string.yelp_token),
getString(R.string.yelp_token_secret));
String result = yelp.searchForBusinessesByLocation("bar", "San Jose, CA");
System.out.println(result);
}
}).start();
有关Android线程的信息,请访问: http://developer.android.com/guide/components/processes-and-threads.html