我想在Android应用程序中向移动设备发送一个localhost服务器,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。 提前感谢您的帮助。
答案 0 :(得分:0)
很可能是NetworkOnMainThreadException,它告诉您在UI线程上进行HTTP连接,并且因为它可能导致无响应,所以不鼓励。
Quick Fix已在其他StackOverflow线程中得到解答,但为了获得更好的解决方案,您需要使用AsyncTask。