Implement HTTP POST and GET Requests on Android

Asked

Viewed 4,720 times

12

How do I send information via get to an Android url, passing parameters? And how do I return data like JSON from my PHP?

  • Have you managed to solve your problem? If any answer is correct for you, mark it as accepted, so other people can be helped.

3 answers

4

The Volley on android to make these requests. Volley is a library in development by google itself to control these requests.

Example using Jsonobjectrequest volley:

RequestQueue queue = Volley.newRequestQueue(this);

final String url = "http://www.seusite.com/get?param1=hello"; 

//Configura a requisicao
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() 
{
    @Override
    public void onResponse(JSONObject response) {   
        // mostra a resposta   
        Log.d("Response", response.toString());
    }
}, 
new Response.ErrorListener() 
{
     @Override
     public void onErrorResponse(VolleyError error) {            
        Log.d("Error.Response", response);
   }
});

// Adiciona a Fila de requisicoes   
queue.add(getRequest);

Here has a well explained tutorial on how to use.

Github Volley The Volley project on Github.

3

Java :

1º First put your parameters in array:

import org.json.JSONArray;
import org.json.JSONObject;

private static final String CAMINHO_URL = "http://www.seusite.br/meuJson.php";
private static final String TAG_MENSAGEM = "mensagem";
private static final String TAG_SUCESSO = "sucesso!";

int sucesso;
MinhaClasseJsonParse jsonParser = new MinhaClasseJsonParse();
List < NameValuePair > meusGETs = new ArrayList < NameValuePair > ();
meusGETs.add(new BasicNameValuePair("meuGET", "MeuValoParaGet"));
meusGETs.add(new BasicNameValuePair("meuSegundoGET", "MeuSegundoValoParaGet"));

JSONObject json = jsonParser.makeHttpRequest(
CAMINHO_URL, "GET", meusGETs);

sucesso = json.getInt(TAG_SUCESSO);
if (sucesso == 1) {
    Log.d("Deu certo!!", json.toString());

    return json.getString(TAG_MESSAGEM);
} else {
    Log.d("Estude mais!", json.getString(TAG_MESSAGEM));
    return json.getString(TAG_MESSAGEM);
}

2º Create a class to run Json. I call it `Minhaclassejsonparse:

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject MinhaClasseJsonParse(String url, String method, List < NameValuePair > params) {

    // Making HTTP request
    try {
        if (method == "GET") {
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
        is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer erro", "Conversão dos erros " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.i("conversor", "[" + jObj + "]");
        Log.e("JSON Parser", "Erro nos dados " + e.toString());
    }

    // return JSON String
    return jObj;

}           

3rd Execute the request :)

new SeuJsonMetodo().execute();

4º Create a PHP code to receive the request via GET:

<?php
if(isset($_GET['meuGet']) or isset($_GET['MeuSegundoValoParaGet'])){

//Retorno em Json do meuGet

$entry = $_GET['meuGet'];
$response["oMeuGetChegou"] = $_GET['meuGet'];
echo json_encode($response);

}

?> 

2

Passing parameters via URL (GET)

1) Use the format http[s]://servidor/pagina.php?chave1=valor1[&chave2=valor2][&chaveN=valorN]

2) read the contents of your keys using $_GET

var_dump( $_GET['chave1'] );

Sending JSON responses via PHP

1) Identify content as JSON

header('Content-Type: application/json');

2) Serialize your content in JSON format, and add the result to sponse

echo json_encode(conteudo);

Sources:

https://stackoverflow.com/questions/7294830/sending-encoding-response-in-json https://stackoverflow.com/questions/4153218/how-to-read-the-query-string-in-php-and-html

Browser other questions tagged

You are not signed in. Login or sign up in order to post.