Implement HTTP POST and GET requests on Android

12

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

    
asked by anonymous 08.12.2014 / 20:20

3 answers

4

The Volley is used on android to make these requisitions. Volley is a library under development by google itself to handle these requests.

Example using JsonObjectRequest from 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 it.

GitHub Volley The volleyball project on GitHub.

    
08.12.2014 / 20:27
3

Java:

First place 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);
}

2nd Create a class to run Json. I call it 'MyClasseJsonParse:

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);

}

?> 
    
08.12.2014 / 21:03
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 the content as JSON

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

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

echo json_encode(conteudo);

Sources:

link link

    
08.12.2014 / 21:54