【发布时间】:2014-03-16 18:58:54
【问题描述】:
今天我开始开发基于 Windows Azure 移动服务的新 Android 应用程序。 我尝试使用微软提供的SDK一整天,没有任何成功。每次应用执行 Web 请求时,此请求都会返回 400,BAD REQUEST 代码。
我去下一层,代码如下。
URL url = new URL("https://xxxx.azure-mobile.net/api/contents"); //host obscured
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
//I obscure the authentication and app key, but they are correct in the program
conn.addRequestProperty("AUTHORIZATION", "Basic xxxxxxxxxxxxxxx");
conn.addRequestProperty("X-ZUMO-APPLICATION", "xxxxxxxxxxxxxxxx");
conn.addRequestProperty("ACCEPT", "application/json");
//connect
conn.connect();
int code = conn.getResponseCode(); //400 in the emulator, 200 in a standard java code
String message = conn.getResponseMessage();
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String read = null;
StringBuilder sb = new StringBuilder();
do {
//Read the content
read = br.readLine();
sb.append(read);
} while(read != null);
//print the content
System.out.println(sb.toString());
//Close the buffers
br.close();
isr.close();
is.close();
System.out.println("Status Code: "+code);
System.out.println(message);
conn.disconnect();
它在标准的 java 应用程序中运行良好,但在模拟器中我仍然收到 400 BAD REQUEST。我真的不明白为什么! 可能是模拟器的问题? 我正在使用 API 10 运行 Android 模拟器。
我想在真实设备上尝试该代码,但 mac 无法识别它...自从我使用它调试应用程序以来,该设备一直工作到昨天。 如果你知道我做错了什么,请帮助我。
2014 年 3 月 20 日编辑:
我做了一些其他的尝试。我尝试使用 HttpClient API。没有运气。
我仍然收到 400 作为响应代码和 Bad Request 作为响应消息。 抛出的异常是 UnknownHostException... 但是 InetAddress.getByName();成功获取我的 Web 服务的 IP 地址。 该应用程序仍然适用于大于 4 的 Android 版本,我尚未尝试使用 Android 3。 我非常难过和沮丧...
感谢您的宝贵时间,
瑞克。
【问题讨论】:
-
你说的 UTF 是什么意思?你能提供参考或类似的东西吗?
-
你从哪里得到你的授权头值,你有没有把 INTERNET 权限放在清单中?您可以发布您尝试使用 SDK 执行的代码吗?
-
我已将 INTERNET 权限放入清单中。我做了一些更深入的测试。我发现它在我的真实设备(Android 4.3)上没有任何问题。相反,在我的一个朋友运行 Android 2.3 的设备上,它仍然给出 400,Bad Requests... :(
-
只是预感 - 尝试在阅读整个回复后致电
getResponseCode。此外,发布通过代理观察到的整个原始 HTTP 请求和响应也会有所帮助。
标签: java android http rest azure-mobile-services