我已成功使用Google教程here,使用Android Studio Servlets模块连接到Google App Engine。我能够在设备上看到Toast消息,这意味着我已成功连接到服务器并收到响应。
我注意到这个模块使用AsyncTask来处理后台任务。根据我的理解,Retrofit是一种在后台线程中处理任务的更简单有效的方法。我基本上试图使用Retrofit 1.9.0而不是他们提供的ServletPostAsyncTask Java类来复制上面提到的Google Tutorial。
以下是我的代码:
MainActivity:
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();
}
});
}
}
Retrofit所需的UserService接口:
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”的Toast(在收到服务器响应之后),就像Google App Engine Servlets模块解释的那样。
现在,我收到以下错误:
对于使用Google App Engine进行Retrofit的任何建议都很受欢迎,因为文档有限。
答案 0 :(得分:0)
首先,您的基本网址应该只是网站的域名http://retrofit-test-1203.appspot.com(它不应包含您尝试访问的资源的路径)所以声明如下:
private static String PROJECT_URL = "http://retrofit-test-1203.appspot.com"
其次,不要使用基本URL(在本例中为PROJECT_URL)作为UserService接口声明中的相对URL。你应该只使用这里的相对URL,即“/ hello”(它必须以斜杠开头),如下所示:
public interface UserService {
@POST("/hello")
void testRequest(@Query("test") String test, Callback<String> cb);
}