我使用Android Studio创建了Google Cloud Endpoint。
我正在测试本地使用后端端点使用HTTP与我的PC中由Android Studio运行的服务器和客户端。
使用Google Cloud Endpoints API Explorer,我可以毫无问题地执行资源“doRegister”。
但是当我尝试在我的应用程序中使用云后端时,我总是在Http请求中收到404错误。我知道我可以使用为Android Studio生成的类来使用Backend,但我想使用HTTP。
我正在使用serverUrl =“http://10.0.2.2:8080/_ah/api/contactEndpoint/v1/doRegister”;但我不知道这是否正确。
拜托,有人可以帮助我,我做错了吗?
Server Backend:
@ApiMethod(name = "doRegister")
public Contact doRegister(@Named("from") String from, @Named("reg_id") String reg_id) {
Contact contact = findRecordByEmail(from);
if (contact == null) {
contact = new Contact(from, reg_id);
try {
contact = this.insertContact(contact);
}
catch (ConflictException e) {
logger.log(Level.SEVERE, e.getMessage());
//return null;
}
} else {
contact.setRegId(reg_id);
}
logger.log(Level.WARNING, "Registered: " + contact.getId());
return contact;
}
Client Backend:
public static void register(final String email, final String regId) {
String serverUrl = "http://10.0.2.2:8080/_ah/api/contactEndpoint/v1/doRegister";
Map<String, String> params = new HashMap<String, String>();
params.put(Common.FROM, email);
params.put(Common.REG_ID, regId);
try {
post(serverUrl, params);
} catch (IOException e) {
}
}
private static void post(String endpoint, Map<String, String> params) throws IOException {
URL url;
try {
url = new URL(endpoint);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("invalid url: " + endpoint);
}
StringBuilder bodyBuilder = new StringBuilder();
Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
// constructs the POST body using the parameters
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
if (iterator.hasNext()) {
bodyBuilder.append('&');
}
}
String body = bodyBuilder.toString();
//Log.v(TAG, "Posting '" + body + "' to " + url);
byte[] bytes = body.getBytes();
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
// post the request
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.close();
// handle the response
int status = conn.getResponseCode();
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
答案 0 :(得分:0)
您需要找到您的PC本地IP地址并用它替换10.0.2.2。
尝试使用Google来查找您的PC本地IP地址。 This article looks promising