Respuesta HTML desde el servidor
Tengo una aplicación que envía algunos de los datos a un servidor local y, como resultado, el servidor enviará un JSON. Decir {status: "success"}
Su funcionamiento cuando corro la aplicación en mi emulador de SDK 2.3, pero instalado en una lengüeta de la galaxia (2.2 SDK) la misma respuesta está en la forma de un html.
- La autenticación de Android HttpClient siempre devuelve código 401
- Envío de archivos mediante POST con HttpURLConnection
- LoopJ AndroidAsyncHttp y JSON POST ARRAY
- Envío de datos JSON de Android a PHP y escritura a archivo de texto
- ¿Cómo usar 'POST' Http Verbo de Woocommerce REST API en JAVA / Android?
I/RESPONSE( 8190): <?xml version="1.0" encoding="utf-8"?> I/RESPONSE( 8190): <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" I/RESPONSE( 8190): "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> I/RESPONSE( 8190): <html> I/RESPONSE( 8190): <head> I/RESPONSE( 8190): <title>417 Expectation Failed</title> I/RESPONSE( 8190): </head> I/RESPONSE( 8190): <body> I/RESPONSE( 8190): <h1>Error 417 Expectation Failed</h1> I/RESPONSE( 8190): <p>Expectation Failed</p> I/RESPONSE( 8190): <h3>Guru Meditation:</h3> I/RESPONSE( 8190): <p>XID: 1902486816</p> I/RESPONSE( 8190): <hr> I/RESPONSE( 8190): <address> I/RESPONSE( 8190): <a href="http://www.varnish-cache.org/">Varnish cache server</a> I/RESPONSE( 8190): </address> I/RESPONSE( 8190): </body> I/RESPONSE( 8190): </html> I/RESPONSE( 8190): <-- I/RESPONSE( 8190): I/RESPONSE( 8190): <?xml version="1.0" encoding="utf-8"?> I/RESPONSE( 8190): <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" I/RESPONSE( 8190): "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> I/RESPONSE( 8190): <html> I/RESPONSE( 8190): <head> I/RESPONSE( 8190): <title>417 Expectation Failed</title> I/RESPONSE( 8190): </head> I/RESPONSE( 8190): <body> I/RESPONSE( 8190): <h1>Error 417 Expectation Failed</h1> I/RESPONSE( 8190): <p>Expectation Failed</p> I/RESPONSE( 8190): <h3>Guru Meditation:</h3> I/RESPONSE( 8190): <p>XID: 1902486816</p> I/RESPONSE( 8190): <hr> I/RESPONSE( 8190): <address> I/RESPONSE( 8190): <a href="http://www.varnish-cache.org/">Varnish cache server</a> I/RESPONSE( 8190): </address> I/RESPONSE( 8190): </body> I/RESPONSE( 8190): </html> W/System.err( 8190): org.json.JSONException: A JSONObject text must begin with '{' at character 2 of W/System.err( 8190): <?xml version="1.0" encoding="utf-8"?> W/System.err( 8190): <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" W/System.err( 8190): "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> W/System.err( 8190): <html> W/System.err( 8190): <head> W/System.err( 8190): <title>417 Expectation Failed</title> W/System.err( 8190): </head> W/System.err( 8190): <body> W/System.err( 8190): <h1>Error 417 Expectation Failed</h1> W/System.err( 8190): <p>Expectation Failed</p> W/System.err( 8190): <h3>Guru Meditation:</h3> W/System.err( 8190): <p>XID: 1902486816</p> W/System.err( 8190): <hr> W/System.err( 8190): <address> W/System.err( 8190): <a href="http://www.varnish-cache.org/">Varnish cache server</a> W/System.err( 8190): </address> W/System.err( 8190): </body> W/System.err( 8190): </html>
Editar: Solicitud de envío: –
try { HttpClient client = new DefaultHttpClient(); String postURL = GlobalCodes.getBaseurl(); HttpPost post = new HttpPost(postURL); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("show", "testpost")); post.setEntity(new UrlEncodedFormEntity(params)); HttpResponse responsePOST = client.execute(post); HttpEntity resEntity = responsePOST.getEntity(); String str2 = EntityUtils.toString(resEntity); Log.i("RESPONSE", " <--"); if (resEntity != null) { Log.i("RESPONSE","**"); JSONObject jsonObj = new JSONObject(str2); if (jsonObj.getString("status").equalsIgnoreCase("succuss")) { ..... } else { ...... } } } catch (Exception e) { e.printStackTrace(); }
Puede alguien decirme lo que va mal?
Codificación feliz ..!
- Android: comprueba si la solicitud es GET o POST
- Android DefaultHTTPConnection con Keep-Alive no reutiliza la conexión TCP
- Los caracteres especiales desaparecen en la solicitud POST desde un teléfono Android
- ¿La intención de Android de publicar la URL?
- Analizar xml de la respuesta httppost
- Retrofit que lanza IllegalArgumentException exception for asynchronous FormUrlEncoded DELETE call
- ¿Cómo calcular el precio en la cantidad de datos JSON y Post datos?
- Configuración del tipo de contenido Json para el cliente Rest
El Galaxy Tab debe estar enviando diferentes encabezados al emulador. Intente deshabilitar el encabezado de expectativa en su objeto HttpPost.
httppost.getParams().setBooleanParameter( "http.protocol.expect-continue", false )
También vea que la espera falló en android durante la subida de fotos
Sólo marque esta línea:
W/System.err( 8190): org.json.JSONException: A JSONObject text must begin with '{' at character 2 of
Estoy seguro de que ha cometido un error al crear / codificar el objeto JSON en el lado del servidor.
No hay nada malo en tu código Java. El problema está en el lado del servidor. Ha ocurrido una vez a mí también, pero mi equipo del servidor cambió el servidor y solucionó el problema.
En resumen, el error HTTP 417 indica que hubo un problema en la transferencia de datos de la aplicación, por lo que el servidor no recibió todos los paquetes que estaba anticipando (o estaban fuera de servicio). Este error sólo se produce por los sitios web que utilizan CheckUpDown. Este es un problema con los servidores de CheckUpDown, por lo que hay poco que puedas hacer. Es posible que desee informar al administrador de wallbase.cc de su problema a través de su foro público.
Parece que el encabezado de aceptar de sus peticiones indica texto / html en lugar de application / json. Cambialo.
Usted consiguió el error from server
que es porqué este tipo de datos consigue en respuesta.
Trate de handle error at server side
, ver qué tipo de servidor de datos recibe cuando envía la solicitud de su aplicación, y cómo manejar el servidor.
EDIT: En mi caso esto funciona,
JSONObject jsonObject = new JSONObject(); jsonObject.put("key1", value1); jsonObject.put("key2", value2); JSONArray jArrayParam = new JSONArray(); jArrayParam.put(jsonObject); List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(); nameValuePair.add(new BasicNameValuePair("bulkdata",jArrayParam.toString())); Log.e("bulkdata", jArrayParam.toString()); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("yor remote server url"); httppost.addHeader("Content-Type", "application/x-www-form-urlencoded"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8)); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); // get response entity HttpEntity entity = response.getEntity(); if (entity != null) { InputStream is = entity.getContent(); // convert stream to string result = convertStreamToString(is); result = result.replace("\n", ""); }
Y este es el método convertStreamToString (es);
public static String convertStreamToString(InputStream is) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); return sb.toString(); }
Tal vez esto es un problema con los valores predeterminados utilizados por DefaultHttpClient (cadena de User-Agent, codificación de transferencia estricta, etc.)? Intente usar AndroidHttpClient
lugar de DefaultHttpClient
. Sus valores por defecto pueden ser más compatibles http://developer.android.com/reference/android/net/http/AndroidHttpClient.html
Si eso no funciona, es posible que tenga que comparar los encabezados HTTP enviados por el iPhone de trabajo, los clientes del emulador a los del cliente Galaxy roto y los ajustes de actualización en consecuencia.
Que es porque el servidor respondió con el html de una página de error – no exactamente json-parseable.
Bien rahul has intentado cualquier tipo diferente de manejo de respuestas para el protocolo HTTP Post
Yo uso algo como esto.
try { String params; String encodedDataLength; connectURL = new URL(_uRL); params = "Blah... Blah... blah; encodedDataLength = "" + params.length(); conn = (HttpURLConnection) connectURL.openConnection(); //conn.setDoInput(true); conn.setDoOutput(true); // signify a post communcation protocol conn.setRequestProperty("User-Agent","mobile"); conn.setRequestProperty("Content-Language", "en-US"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty( "Content-Length", encodedDataLength); //System.out.println("con :" + conn); os = conn.getOutputStream(); os.write(params.getBytes()); os.flush(); // Getting the response code will open the connection, // send the request, and read the HTTP response headers. // The headers are stored until requested. is = conn.getInputStream(); // get session from the cookie String cookie = conn.getHeaderField("cookie"); if (cookie != null) { session = cookie; } // Get the length and process the data BufferedReader br = new BufferedReader(new InputStreamReader(is)); responseString = br.readLine(); //System.out.println(responseString); } catch (Exception e) { //java.lang.System.out.println("http exception: " + e.printStackTrace()); } finally { try { if (is != null) is.close(); if (os != null) os.close(); if (conn != null) conn.disconnect(); } catch (Exception e) { e.printStackTrace(); } }
Después de esto se hace … sólo puede insertar cualquier metodología de decodificación Json para recuperar los datos de la cadena llamada resposeString.
A continuación se muestran los archivos de importación incluidos para esta implementación. Sé que hay diferentes para ésos.
import java.io.*; import java.net.URL; import java.net.HttpURLConnection; import java.util.zip.GZIPInputStream; import java.lang.String;
- Cómo mantener la versión gratuita / pagada de la aplicación separada en subversión
- FrameLayout layout_weight de forma programática