我想从 Android 应用程序向我的网络服务器发送 json 数据。因此,我编写了以下方法:
@Override
protected String doInBackground(String... params) {
String id = Configuration.getUserId();
String date = sdf.format( new Date() );
String type = "message";
String message = params[0];
try {
JSONObject json = new JSONObject();
json.put( "id", id);
json.put( "date", date );
json.put( "type", type );
json.put( "message", message );
byte[] postData = URLEncoder.encode( json.toString(), "UTF-8" ).getBytes();
URL url = new URL( Configuration.loggingURL );
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
//conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(postData.length));
conn.setUseCaches(false);
DataOutputStream out = new DataOutputStream ( conn.getOutputStream () );
out.write(postData);
out.flush();
out.close();
conn.disconnect();
} catch( Exception e ) {
e.printStackTrace();
}
Log.d("RemoteLogging","Data sent.");
return null;
}
在服务器端,我有这样的事情:
public class LoggingServlet extends HttpServlet {
private static final long serialVersionUID = 2L;
@Override
public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
{
System.out.println("LoggingServlet: doPost got called");
但是,这不起作用,没有数据到达我的服务器。doPost 方法甚至没有被调用(即,我在我的 tomcat 服务器的日志中什么也看不到)。我还有一个 iPhone 应用程序可以成功地将数据发送到我的服务器,并且我在浏览器中测试了 Configuration.loggingURL 以便我可以确定它是正确的调用 URL。
我在这里做错了什么?
更新:我刚刚检查了 Wireshark 没有来自 Android 应用程序的传出流量(在模拟器中运行)。所以什么都没有发送。