Foros del Web » Programando para Internet » Android »

wcf rest envio de tildes y enies

Estas en el tema de wcf rest envio de tildes y enies en el foro de Android en Foros del Web. Hola foro aquí un problema que no le encontrado solución ps tengo un servicio wcf rest en un iis7 esta es mi simple interfaz @import ...
  #1 (permalink)  
Antiguo 08/02/2012, 18:58
 
Fecha de Ingreso: enero-2011
Ubicación: lima-peru
Mensajes: 80
Antigüedad: 13 años, 3 meses
Puntos: 4
Exclamación wcf rest envio de tildes y enies

Hola foro

aquí un problema que no le encontrado solución
ps tengo un servicio wcf rest en un iis7

esta es mi simple interfaz

Código C++:
Ver original
  1. [ServiceContract]
  2.     public interface ISAERegistro
  3.     {
  4.         #region "test"
  5.  
  6.         [OperationContract]
  7.         [WebInvoke(
  8.             Method = "PUT",
  9.             RequestFormat = WebMessageFormat.Json,
  10.             ResponseFormat = WebMessageFormat.Json,
  11.             UriTemplate = "/testSendGetObject",
  12.             BodyStyle = WebMessageBodyStyle.WrappedRequest)]
  13.         TestEntity testSendObject(TestEntity sendGetObject);
  14.  
  15.         [OperationContract]
  16.         [WebInvoke(
  17.             Method = "PUT",
  18.             RequestFormat = WebMessageFormat.Json,
  19.             ResponseFormat = WebMessageFormat.Json,
  20.             UriTemplate = "/testAloneSendObject",
  21.             BodyStyle = WebMessageBodyStyle.Wrapped)]
  22.         void testAloneSendObject(TestEntity sendObject);
  23.  
  24.         [OperationContract]
  25.         [WebGet(
  26.             UriTemplate = "/testAloneGetObject",
  27.             ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json,
  28.             BodyStyle = WebMessageBodyStyle.WrappedRequest
  29.             )]        
  30.         TestEntity testAloneGetObject();
  31.  
  32.  
  33.         [OperationContract]
  34.         [WebInvoke(
  35.             Method = "PUT",
  36.             RequestFormat = WebMessageFormat.Json,
  37.             ResponseFormat = WebMessageFormat.Json,
  38.             UriTemplate = "/testSendGetString/{sendGetString}",
  39.             BodyStyle = WebMessageBodyStyle.WrappedRequest)]
  40.         string testSendGetString(string sendGetString);
  41.  
  42.         [OperationContract]
  43.         [WebInvoke(
  44.             Method = "PUT",
  45.             RequestFormat = WebMessageFormat.Json,
  46.             ResponseFormat = WebMessageFormat.Json,
  47.             UriTemplate = "/testAloneSendString/{sendString}",
  48.             BodyStyle = WebMessageBodyStyle.Wrapped)]
  49.         void testSendString(string sendString);
  50.  
  51.         [OperationContract]
  52.         [WebGet(
  53.             UriTemplate = "/testAloneGetString",
  54.             ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json
  55.             )]
  56.         string testGetString();
  57.  
  58.         #endregion
  59.  
  60.      
  61.     }


la entidad
Código vb:
Ver original
  1. namespace LuzDelSur.Tecnico.SAE.Registro.WCFEntity
  2. {
  3.     [DataContract( Name="TestEntity " , Namespace="") ]
  4.     public class TestEntity
  5.     {
  6.        
  7.           [DataMember( Name="nombre", Order=1)]
  8.         public string nombre  { get; set; }        
  9.          [DataMember (Name="algo" , Order=2) ]
  10.         public string algo  { get; set; }
  11.        
  12.      
  13.    }
  14.  
  15.  
  16. }

y la implementacion del servicio

Código C++:
Ver original
  1. public class SAERegistro : ISAERegistro
  2.     {
  3.        
  4.        
  5.         #region "test"
  6.  
  7.         public TestEntity testSendObject(TestEntity sendGetObject) {
  8.             return sendGetObject;
  9.         }
  10.  
  11.         public void testAloneSendObject(TestEntity sendObject) {
  12.             //:D
  13.         }
  14.  
  15.         public TestEntity testAloneGetObject() {
  16.             TestEntity tes = new TestEntity();
  17.             tes.algo = "abcdefghijklmnñopqrstuvwxyz";
  18.             tes.nombre = "´qweeraáéíóúñÑ!#$$%$&%&/(&?=))=(()/(&/%(/&°¬°/*'";
  19.             return tes;
  20.         }
  21.  
  22.         public string testSendGetString(string sendGetString) {
  23.             return sendGetString;
  24.         }
  25.         public void testSendString(string sendString) {
  26.             //:D
  27.         }
  28.         public string testGetString(){
  29.             return "´qweeraáéíóúñÑ!#$$%$&%&/(&?=))=(()/(&/%(/&°¬°/*'";
  30.         }
  31.  
  32.  
  33.         #endregion
  34.  
  35.      
  36.     }

y mi cliente en android


Código Javascript:
Ver original
  1. httpClient = HttpClientFactory.getDefaultHttpClient();
  2.    
  3.                
  4.         T salida = null;
  5.         String aux = urlServidor + "/" + servicio.toString();
  6.         aux = aux.trim();
  7.  
  8.         /**
  9.          * este esplit se hace para formatear la peticion a una URI valida este
  10.          * error se daba por ejeplo se daba una paametro con acentos o espacios
  11.          */
  12. //      String[] parts = aux.split(":");
  13. //     
  14. //      if(port!=null){
  15. //          parts[1]+=":"+port+"/"+servicio.toString();
  16. //      }
  17. //     
  18. //          URI uri = new URI(parts[0], parts[1], null);
  19.  
  20.         aux = (URI.create(aux)).toString();
  21.  
  22.         StringEntity input = new StringEntity("{" + entityRequest.toString()
  23.                 + "}");
  24.  
  25.        
  26.         input.setContentType("application/json;charset=ISO-8859-1");// text/plain;charset=UTF-8
  27.  
  28.    
  29.        
  30.         testingMonitor.writeLog("test", "URI parseada:" + aux);
  31.         testingMonitor.writeLog("test", "entity a ser enviada :: {"
  32.                 + entityRequest.toString() + "}");
  33.  
  34.         switch (metodo) {
  35.        
  36.         case RestClientConstants.Metodo.PUT:
  37.             testingMonitor.writeLog("test", ">PUT");
  38.             HttpPut putRequest = new HttpPut(aux);
  39.  
  40.         //  putRequest.setHeader("Accept", "text/json");
  41.             putRequest.setHeader("Content-type", "text/json; charset=ISO-8859-1");
  42.            
  43.             if (!input.equals("{}")) {
  44.                 //input.setContentType("text/json");
  45.                 putRequest.setEntity(input);
  46.                 testingMonitor.writeLog("test", "aniadio entity");
  47.             } else {
  48.                 testingMonitor.writeLog("test", "no aniadio entity");
  49.             }
  50.  
  51.             response = ejecutarMetodoSincrono(putRequest);
  52.             // br = new BufferedReader( new
  53.             // InputStreamReader((response.getEntity().getContent())));
  54.  
  55.             // limpiar el entytiRequest al final de la petición
  56.  
  57.             break;
  58.  
  59.         }
  60.    
  61.         br = new BufferedReader( new InputStreamReader((response.getEntity().getContent())));
  62.        
  63.         entityRequest.delete(0, entityRequest.length());
  64.         servicio = new StringBuilder();
  65.  
  66.         testingMonitor.writeLog("test", "estatus code:"
  67.                 + response.getStatusLine().getStatusCode());
  68.  
  69.         if (response.getStatusLine().getStatusCode() != 200) {
  70.  
  71.                         String json=br.readLine();
  72.        
  73.            
  74.                     throw new RuntimeException("Failed : HTTP error code : "
  75.                         + response.getStatusLine().getStatusCode());
  76.  
  77.         }
  78.  
  79.         if (c != null) {
  80.             String json=br.readLine();
  81. //          String json = br;
  82.             json = json.trim();
  83.             testingMonitor.writeLog("test", "json repuesta:" + json);
  84.             if (json.length() > 0) {
  85.                 salida = (T) gs.fromJson(json, c);
  86.             }
  87.             testingMonitor.writeLog("test",
  88.                     "salida clase parseada :" + salida.toString());
  89.         }
  90.  
  91.        
  92.         return salida;
  93.     }

basicamente , tiene mas codigo pero eso es lo que ejecuta para consumir el servicio , todo ok mientras no halla carcater como la enie o tildes ,

cuando envio y recibo string con simbolos raros no problemas
el problema es cuando el estring esta dentro de una clase como atributo , el esrvidor me reopnde con code estatus 400

.aniado l codigo que parsea el objeton

Código C++:
Ver original
  1. @Override
  2.     public void addObjetoRequest(String var, Object obj) {
  3.         entityRequest.append("\"");
  4.         entityRequest.append(var);
  5.         entityRequest.append("\":");
  6.         entityRequest.append(gs.toJson(obj));
  7.     }

alguien le ha pasado? ...qeu encoder reibe el servicio wcf , talves tenga que configurar su web config . nose ,.espero alguna luz sobre esto , gracias.
  #2 (permalink)  
Antiguo 16/02/2012, 04:15
 
Fecha de Ingreso: junio-2003
Ubicación: Asturias
Mensajes: 2.429
Antigüedad: 20 años, 10 meses
Puntos: 7
Respuesta: wcf rest envio de tildes y enies

Hola SolisUNMSM,

Perdona que te moleste, por que no tenguna solución a tu problema, pero... viendo que dominas algo el tema de WCF con Android, me gustaría preguntarte si usas ese webservice con https, y si es así, como lo haces, por que yo lo intenté con HttpsTransportSE, pero me daba error.

¿Sabes algo del tema?, y... aprovechando, jeje... ¿Sabes algo de como meter autentificación por parte de Android?, Sé crear un WCF seguro, que pida usuario y clave, pero... no sabría como ponerlo en la llamada desde Android.

Si me pudieras orientar en alguno de los dos campos, te lo agradecería mucho, la verdad. Y, nuevamente te pido disculpas por haberte hecho entrar aqui, sin tener una respuesta a tu problema, de la cual, la verdad, no tengo ni idea.

Gracias.
__________________
Charlie.
  #3 (permalink)  
Antiguo 12/03/2012, 23:09
 
Fecha de Ingreso: enero-2011
Ubicación: lima-peru
Mensajes: 80
Antigüedad: 13 años, 3 meses
Puntos: 4
De acuerdo Respuesta: wcf rest envio de tildes y enies

Cita:
Iniciado por chcma Ver Mensaje
Hola SolisUNMSM,

Perdona que te moleste, por que no tenguna solución a tu problema, pero... viendo que dominas algo el tema de WCF con Android, me gustaría preguntarte si usas ese webservice con https, y si es así, como lo haces, por que yo lo intenté con HttpsTransportSE, pero me daba error.

¿Sabes algo del tema?, y... aprovechando, jeje... ¿Sabes algo de como meter autentificación por parte de Android?, Sé crear un WCF seguro, que pida usuario y clave, pero... no sabría como ponerlo en la llamada desde Android.

Si me pudieras orientar en alguno de los dos campos, te lo agradecería mucho, la verdad. Y, nuevamente te pido disculpas por haberte hecho entrar aqui, sin tener una respuesta a tu problema, de la cual, la verdad, no tengo ni idea.

Gracias.
(todo es segun investigue y me funciono) Si el servidor tiene un certificado reconocido por alguna entidad de certificacion como Verisign u otro , este deberia estar en el repositorio de certificados de tu dispositivo android , igual para los emuladores , hay una negociacion previa , entre la entidad-tu servidor- tu cliente(amdroid) , todo para usar una conexion segura , para lo cual solo debe indicar en el httpCLient que vas usar de ese tipo . como?

para usar https

HttpClient httpclient = new HttpClient();
GetMethod httpget = new GetMethod("https://www.verisign.com/");
try {
httpclient.executeMethod(httpget);
System.out.println(httpget.getStatusLine());
} finally {
httpget.releaseConnection();
}

MAS INFO : http://hc.apache.org/httpclient-3.x/sslguide.html

y para la auntetificacion


Código Javascript:
Ver original
  1. public class ClientAuthentication {
  2.  
  3.     public static void main(String[] args) throws Exception {
  4.         DefaultHttpClient httpclient = new DefaultHttpClient();
  5.         try {
  6.             httpclient.getCredentialsProvider().setCredentials(
  7.                     new AuthScope("localhost", 443),
  8.                     new UsernamePasswordCredentials("username", "password"));
  9.  
  10.             HttpGet httpget = new HttpGet("https://localhost/protected");
  11.  
  12.             System.out.println("executing request" + httpget.getRequestLine());
  13.             HttpResponse response = httpclient.execute(httpget);
  14.             HttpEntity entity = response.getEntity();
  15.  
  16.             System.out.println("----------------------------------------");
  17.             System.out.println(response.getStatusLine());
  18.             if (entity != null) {
  19.                 System.out.println("Response content length: " + entity.getContentLength());
  20.             }
  21.             EntityUtils.consume(entity);
  22.         } finally {
  23.             // When HttpClient instance is no longer needed,
  24.             // shut down the connection manager to ensure
  25.             // immediate deallocation of all system resources
  26.             httpclient.getConnectionManager().shutdown();
  27.         }
  28.     }
  29. }

MAS INFO : http://hc.apache.org/httpclient-3.x/...Authentication


...ahora si no.je son mas pasos pero me ayudo a comprender mas paso a paso lo que hace android .

te dara error de NO TRUSTED , para lo cual tienes tienes que darle el certifcado a; android tomandolo de tu server asi lA negociacion ya solo seria de los dos

son muchos pasos , te dejo el link donde esta explicados , son los que segui

http://blog.antoine.li/2010/10/22/an...-certificates/

..ALGO MAS , android para una nueva version esta haciendo un apquete especialmente para su SO , sobre en el httpClient , yo lo ise con el actual , ps no me habia enterado , la idea es la misma , aqui lo mencionan

http://android-developers.blogspot.c...p-clients.html


suerte .
  #4 (permalink)  
Antiguo 13/03/2012, 01:37
 
Fecha de Ingreso: junio-2003
Ubicación: Asturias
Mensajes: 2.429
Antigüedad: 20 años, 10 meses
Puntos: 7
Respuesta: wcf rest envio de tildes y enies

Jajajajaja, eso es lo que llamo una respuesta completa.

Muchas gracias.
__________________
Charlie.

Etiquetas: error400, rest, services, wcf
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 04:00.