2010-12-28 15 views
40

Tengo que hacer una solicitud posterior http a un servicio web para autenticar al usuario con nombre de usuario y contraseña. El chico del servicio web me dio la siguiente información para construir la solicitud de HTTP Post.Android, Java: HTTP POST Request

POST /login/dologin HTTP/1.1 
Host: webservice.companyname.com 
Content-Type: application/x-www-form-urlencoded 
Content-Length: 48 

id=username&num=password&remember=on&output=xml 

la respuesta XML que va a obtener es

<?xml version="1.0" encoding="ISO-8859-1"?> 
<login> 
<message><![CDATA[]]></message> 
<status><![CDATA[true]]></status> 
<Rlo><![CDATA[Username]]></Rlo> 
<Rsc><![CDATA[9L99PK1KGKSkfMbcsxvkF0S0UoldJ0SU]]></Rsc> 
<Rm><![CDATA[b59031b85bb127661105765722cd3531==AO1YjN5QDM5ITM]]></Rm> 
<Rl><![CDATA[[email protected]]]></Rl> 
<uid><![CDATA[3539145]]></uid> 
<Rmu><![CDATA[f8e8917f7964d4cc7c4c4226f060e3ea]]></Rmu> 
</login> 

Esto es lo que estoy haciendo HttpPost postRequest = new HttpPost (urlString); ¿Cómo construyo el resto de los parámetros?

Respuesta

81

Aquí hay un ejemplo encontrado anteriormente en androidsnippets.com (el sitio no se mantiene actualmente).

// Create a new HttpClient and Post Header 
HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php"); 

try { 
    // Add your data 
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
    nameValuePairs.add(new BasicNameValuePair("id", "12345")); 
    nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!")); 
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

    // Execute HTTP Post Request 
    HttpResponse response = httpclient.execute(httppost); 

} catch (ClientProtocolException e) { 
    // TODO Auto-generated catch block 
} catch (IOException e) { 
    // TODO Auto-generated catch block 
} 

Entonces, puede agregar sus parámetros como BasicNameValuePair.

Una alternativa es usar (Http)URLConnection. Consulte también Using java.net.URLConnection to fire and handle HTTP requests. Este es realmente el método preferido en las versiones más nuevas de Android (Gingerbread +). Vea también this blog, this developer doc y Android HttpURLConnection javadoc.

+1

¿Hay alguna manera fácil de agregar matrices? ¿Debería recorrerlos y agregar el par BasicNameValuePair ("array []", array [i])? – gsingh2011

+1

¿También es efectivo en archivos JSON en lugar de en XML? –

+2

Para Android 2.3 y versiones posteriores, Google recomienda utilizar HttpURLConnection. http://developer.android.com/reference/org/apache/http/impl/client/DefaultHttpClient.html –

0

Trate HttpClient para Java:

http://hc.apache.org/httpclient-3.x/

+1

¿Echas de menos la etiqueta 'Android'? ¡Ya está usando (una versión litera) de HttpClient bajo las sábanas! Consulte también [HttpPost javadoc] (http://developer.android.com/reference/org/apache/http/client/methods/HttpPost.html). – BalusC

2

Por favor, considere el uso de HttpPost. Adoptar de esto: http://www.javaworld.com/javatips/jw-javatip34.html

URLConnection connection = new URL("http://webservice.companyname.com/login/dologin").openConnection(); 
// Http Method becomes POST 
connection.setDoOutput(true); 

// Encode according to application/x-www-form-urlencoded specification 
String content = 
    "id=" + URLEncoder.encode ("username") + 
    "&num=" + URLEncoder.encode ("password") + 
    "&remember=" + URLEncoder.encode ("on") + 
    "&output=" + URLEncoder.encode ("xml"); 
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 

// Try this should be the length of you content. 
// it is not neccessary equal to 48. 
// content.getBytes().length is not neccessarily equal to content.length() if the String contains non ASCII characters. 
connection.setRequestProperty("Content-Length", content.getBytes().length); 

// Write body 
OutputStream output = connection.getOutputStream(); 
output.write(content.getBytes()); 
output.close(); 

que se necesitan para detectar la excepción a sí mismo.

+0

¿Cómo imprimo la respuesta? – Tamil

5

a la respuesta @BalusC yo añadiría cómo convertir la respuesta en una cadena:

HttpResponse response = client.execute(request); 
HttpEntity entity = response.getEntity(); 
if (entity != null) { 
    InputStream instream = entity.getContent(); 

    String result = RestClient.convertStreamToString(instream); 
    Log.i("Read from server", result); 
} 

Here is an example of convertStramToString.

0

He utilizado el siguiente código para enviar HTTP POST desde mi aplicación cliente de Android a C# aplicación de escritorio en mi servidor:

// Create a new HttpClient and Post Header 
HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php"); 

try { 
    // Add your data 
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
    nameValuePairs.add(new BasicNameValuePair("id", "12345")); 
    nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!")); 
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

    // Execute HTTP Post Request 
    HttpResponse response = httpclient.execute(httppost); 

} catch (ClientProtocolException e) { 
    // TODO Auto-generated catch block 
} catch (IOException e) { 
    // TODO Auto-generated catch block 
} 

trabajé en la lectura de la solicitud de un # aplicación C en mi servidor (algo así como una pequeña aplicación de servidor web). logré leer Solicitud publicada de datos utilizando el siguiente código:

server = new HttpListener(); 
server.Prefixes.Add("http://*:50000/"); 
server.Start(); 

HttpListenerContext context = server.GetContext(); 
HttpListenerContext context = obj as HttpListenerContext; 
HttpListenerRequest request = context.Request; 

StreamReader sr = new StreamReader(request.InputStream); 
string str = sr.ReadToEnd(); 
1

prefiero recomiendo usar voleo hacer GET, PUT, POST ... solicitudes.

Primero, agregue dependencia en su archivo gradle.

compile 'com.he5ed.lib:volley:android-cts-5.1_r4'

Ahora, utilice este fragmento de código para hacer peticiones.

RequestQueue queue = Volley.newRequestQueue(getApplicationContext()); 

     StringRequest postRequest = new StringRequest(com.android.volley.Request.Method.POST, mURL, 
       new Response.Listener<String>() 
       { 
        @Override 
        public void onResponse(String response) { 
         // response 
         Log.d("Response", response); 
        } 
       }, 
       new Response.ErrorListener() 
       { 
        @Override 
        public void onErrorResponse(VolleyError error) { 
         // error 
         Log.d("Error.Response", error.toString()); 
        } 
       } 
     ) { 
      @Override 
      protected Map<String, String> getParams() 
      { 
       Map<String, String> params = new HashMap<String, String>(); 
       //add your parameters here as key-value pairs 
       params.put("username", username); 
       params.put("password", password); 

       return params; 
      } 
     }; 
     queue.add(postRequest);