【发布时间】:2016-01-27 18:53:54
【问题描述】:
我已成功遵循 Google 教程 here,使用 Android Studio Servlets 模块连接到 Google App Engine。我能够在我的设备上看到 Toast 消息,这意味着我已成功连接到服务器并收到了响应。
我注意到这个模块使用 AsyncTask 来处理后台任务。据我了解,Retrofit 是一种在后台线程中处理任务的更简单有效的方法。我基本上是在尝试使用 Retrofit 1.9.0 而不是他们提供的 ServletPostAsyncTask Java 类来复制上面提到的 Google 教程。
下面是我的代码:
主活动:
public class MainActivity extends AppCompatActivity {
//set the URL of the server, as defined in the Google Servlets Module Documentation
private static String PROJECT_URL = "http://retrofit-test-1203.appspot.com/hello";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Instantiate a new RestAdapter Object, setting the endpoint as the URL of the server
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(PROJECT_URL)
.build();
//Instantiate a new UserService object, and call the "testRequst" method, created in the interface
//to interact with the server
UserService userService = restAdapter.create(UserService.class);
userService.testRequest("Test_Name", new Callback<String>() {
@Override
public void success(String s, Response response) {
Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
}
@Override
public void failure(RetrofitError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
改造所需的用户服务接口:
public interface UserService {
static String PROJECT_URL = "http://retrofit-test-1203.appspot.com/hello";
@POST(PROJECT_URL)
void testRequest(@Query("test") String test, Callback<String> cb);
}
我的 Servlet,按照 Google Servlets 模块的要求:
public class MyServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/plain");
resp.getWriter().println("Please use the form to POST to this url");
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
String name = req.getParameter("name");
resp.setContentType("text/plain");
if(name == null) {
resp.getWriter().println("Please enter a name");
}
resp.getWriter().println("Hello " + name);
}
}
在我的 userService.testRequest() 方法中,我将“Test_Name”作为字符串参数传入。这段文本是我希望传递给服务器的,然后看到一个显示“Hello Test_Name”的吐司(在收到服务器响应后),就像 Google App Engine Servlets 模块解释的那样。
现在,我收到以下错误:
感谢任何有关将 Retrofit 与 Google App Engine 结合使用的建议,因为文档有限。
【问题讨论】:
-
嘿@tccpg288,你搞定了吗?我正在努力使用谷歌端点生成的库进行改造。
标签: java google-app-engine android-studio retrofit