2

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

问题

在我将内容类型设置为 application/json 的 get 方法中,android 客户端出现问题,但 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)
4

3 回答 3

2

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

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

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

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

于 2013-09-18T16:16:17.880 回答
0

您应该为此使用 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();
                   }

                }
            }
于 2015-02-20T19:58:24.703 回答
0

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

 //get.setHeader("Content-Type", "application/json");
于 2013-09-18T16:11:21.337 回答