【问题标题】:Android Web Services Client (JSON)Android 网络服务客户端 (JSON)
【发布时间】:2013-09-23 12:03:21
【问题描述】:

我正在开发一个 android 应用程序,此应用程序是在 glassfish 3.1.2.2 中运行的 Web 服务的客户端,此 Web 服务与 xml 和 json 解析器一起使用,我在外部测试 de WS 以查看我得到的答案和当我从服务器查找 xml 答案时,我得到了 xml 数据,Json 答案也是如此。

问题

android客户端在get方法中出现问题,我将content-type设置为application/json,但WS只响应xml。

谁能告诉我哪里做错了,我会把代码放在最后登录。

代码:-

private class TareaWSObtener extends AsyncTask<String, Integer, Boolean>{

        //CONSTANTES
        private static final String CONTENT = "Content-Type"; //content-type
        private static final String JSONTYPE = "application/json"; //application/json
        private static final String LOGWS = "MovilSecure:WebServices";
        private int id;
        private String nombre;

        @Override
        protected Boolean doInBackground(String... params) {
            // TODO Auto-generated method stub
            boolean result = true;

            Log.i(LOGWS, "Levantando cliente");
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet get = new HttpGet("http://10.0.2.2:8080/WS-MovilSecure_SandBox_ONLY_/webresources/persona");
            //get.setHeader("Content-Type", "application/json");
            Log.i(LOGWS, "cliente levantado");
            try{
                Log.i(LOGWS, "Obteniendo data");
                HttpResponse resp = httpClient.execute(get);

                String stringRsp = EntityUtils.toString(resp.getEntity());
                JSONObject respJSON = new JSONObject(stringRsp);

                id = respJSON.getInt("idPersona");
                nombre = respJSON.getString("nombre");
                Log.i(LOGWS, "Data Obtenida");

            }
            catch(Exception e){
                Log.e(LOGWS, "Problemas al conectar con el WS", e);
                result = false;
            }

            return result;
        }

        protected void onPostExecute(boolean result){
            if(result){Log.i(LOGWS, "data:"+id+nombre);}
        }

    }

日志:-

09-13 21:52:50.073: I/MovilSecure:WebServices(3155): Levantando cliente
09-13 21:52:50.123: I/MovilSecure:WebServices(3155): cliente levantado
09-13 21:52:50.123: I/MovilSecure:WebServices(3155): Obteniendo data
09-13 21:52:50.293: E/MovilSecure:WebServices(3155): Problemas al conectar con el WS
09-13 21:52:50.293: E/MovilSecure:WebServices(3155): org.json.JSONException: Value <?xml       of type java.lang.String cannot be converted to JSONObject
09-13 21:52:50.293: E/MovilSecure:WebServices(3155):    at org.json.JSON.typeMismatch(JSON.java:111)
09-13 21:52:50.293: E/MovilSecure:WebServices(3155):    at org.json.JSONObject.<init>(JSONObject.java:158)
09-13 21:52:50.293: E/MovilSecure:WebServices(3155):    at org.json.JSONObject.<init>(JSONObject.java:171)
09-13 21:52:50.293: E/MovilSecure:WebServices(3155):    at com.example.wsclient_movilesecure.MainActivity$TareaWSObtener.doInBackground(MainActivity.java:110)
09-13 21:52:50.293: E/MovilSecure:WebServices(3155):    at com.example.wsclient_movilesecure.MainActivity$TareaWSObtener.doInBackground(MainActivity.java:1)
09-13 21:52:50.293: E/MovilSecure:WebServices(3155):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
09-13 21:52:50.293: E/MovilSecure:WebServices(3155):    at java.util.concurrent.FutureTask.run(FutureTask.java:234)
09-13 21:52:50.293: E/MovilSecure:WebServices(3155):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
09-13 21:52:50.293: E/MovilSecure:WebServices(3155):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
09-13 21:52:50.293: E/MovilSecure:WebServices(3155):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
09-13 21:52:50.293: E/MovilSecure:WebServices(3155):    at java.lang.Thread.run(Thread.java:841)

【问题讨论】:

  • Accept 标头呢?

标签: java android xml json web-services


【解决方案1】:

您想要设置 Accept 标头。你可以在这里阅读:http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html

“Accept request-header 字段可用于指定响应可接受的某些媒体类型。”

get.setHeader("Accept", "application/json");

Content-Type 标头用于指示您发送的数据类型。对于 GET 请求,您的请求没有正文。在这种情况下,您不需要设置 Content-Type

【讨论】:

  • 谢谢你是对的,我不知道关于标题我会调查更多,非常感谢。
【解决方案2】:

我不知道这是否是一个错误,但请尝试取消注释此行

 //get.setHeader("Content-Type", "application/json");

【讨论】:

    【解决方案3】:

    您应该为此使用 robospice 库。我和你一样消耗服务器资源,当你使用 3g 或者你转动你的智能手机或平板电脑时,这是不一致的,糟糕的响应,这会破坏你的应用程序。

    无论如何,这是我的代码和一个简单的示例:

    (这是一个很好的做法,3 个意图,如果结束则关闭连接)

        boolean ok = false;
         String insertar = "http://www.SuperCalifragi.net/api/Registro/Registro";
                for(int i = 0 ; i < 3 ; i++)
                {
                    HttpURLConnection connection = null;
                     try {
                        URL url = new URL(insertar);
                        connection =  (HttpURLConnection) url.openConnection();
                        connection.setDoOutput(true);
                        connection.setRequestMethod("POST");
                        connection.setRequestProperty("Content-Type", "application/json");
                        connection.setConnectTimeout(5000);
                        Gson gson = new Gson();
                        String input = gson.toJson(user,RegistroUsuarioViewModel.class);      
                        System.out.println("enviamos: "+input);
    
                        OutputStream os = connection.getOutputStream();             
                        os.write(input.getBytes());
                        os.flush();
    
                        String response = "";  
                        if (connection.getResponseCode() != 200) {  
                          response = "Error From Server \n\n";  
                        } else {  
                          response = "Response From Server \n\n";  
                        }   
                        System.out.println("responsee: "+response + " - "+connection.getResponseCode());
                        BufferedReader responseBuffer = new BufferedReader(new InputStreamReader((connection.getInputStream())));
    
                        String output ="";
                        while ((output = responseBuffer.readLine()) != null) {
                            resultadoRegistro = resultadoRegistro + output;
                        }            
                        con = gson.fromJson(resultadoRegistro, Conexion.class);
                        System.out.println("CONTENIDO: "+con);
                        ok = true;
                    } catch(SocketTimeoutException e){
    
                    } catch (MalformedURLException ex) {
                    } catch (IOException ex) {
                    } catch(Exception e){           
                    }finally{
                        if( i > 3 && connection != null){
                            connection.disconnect();
                        }if(ok){
                         i = 10; //break loop
                         connection.disconnect();
                       }
    
                    }
                }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-30
      • 1970-01-01
      • 2011-08-10
      • 2012-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多