【发布时间】:2015-08-21 23:13:30
【问题描述】:
我想在 Android 应用程序中从移动设备向本地主机服务器发送 json 数据。 我使用真实的手机作为客户端来测试我的应用程序。 我使用 API Rest 发送数据,使用 Servlet 接收数据。
连接出错,手机连接不上服务器,不知道为什么...
这是客户端代码:
public void send(){
StringBuilder sb = new StringBuilder();
String http = "http://10.0.2.2/W7TurismoServer/Servlet";
ArrayList<String> mostraArray=show();
HttpURLConnection urlConnection=null;
try {
URL url = new URL(http);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.setConnectTimeout(10000);
urlConnection.setReadTimeout(10000);
urlConnection.setRequestProperty("Content-Type","application/json");
urlConnection.setRequestProperty("Host","http://10.0.2.2/W7TurismoServer/Servlet");
urlConnection.connect();
//Create JSONObject here*/
JSONObject jsonParam = new JSONObject();
JSONArray arraypref=new JSONArray();
arraypref.put(mostraArray);
jsonParam.put("stringList",arraypref);
System.out.println(jsonParam);
OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
out.write(jsonParam.toString());
out.close();
int HttpResult =urlConnection.getResponseCode();
if(HttpResult ==HttpURLConnection.HTTP_OK){
BufferedReader br = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream(),"utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
System.out.println(""+sb.toString());
}else{
System.out.println(urlConnection.getResponseMessage());
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(urlConnection!=null)
urlConnection.disconnect();
}
}
show() 方法返回 ArrayList,我会将这个数组发送到服务器。
这是服务器代码:
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out= response.getWriter();
out.println("sono11");
System.out.println("stouk do");
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { /*report an error*/ }
try {
JSONObject jsonObject = JSONObject.fromObject(jb.toString());
System.out.println("sono venuto,"+jsonObject);
} catch (ParseException e) {
// crash and burn
throw new IOException("Error parsing JSON request string");
}
}
}
这个类在 W7TurismoServer 中。 提前感谢您的帮助。
【问题讨论】:
-
没有错误信息。应用程序在“urlConnection.connect();”之后被阻止在客户端。
-
logcat 中有没有消息?
-
这里程序停止:}finally{ if(urlConnection!=null) urlConnection.disconnect(); }
-
尝试删除 finally 块。每次 urlConnection != null 时它都会断开连接。
标签: android json servlets mobile server