How to receive data via POST, sent from android to webservice PHP?

4

I've done a webservice in java, now I'm switching to PHP and I'm having trouble implementing a page that receives via POST a JSON that the Android app sends.

ANDROID

public static String POST(Context context, String endereco, String json){
    //Verifica se existe conexão com a internet
    if(!existeConexao(context))
        return K.FALHA_CONEXAO;

    InputStream inputStream = null;
    HttpClient httpClient = new DefaultHttpClient();
    String result = null;
    try{
        HttpPost httpPost = new HttpPost(endereco);
        httpPost.setEntity(new StringEntity(json, "UTF-8"));
        httpPost.setHeader("Accept","application/json");
        httpPost.setHeader("Content-type", "application/json");

        HttpResponse httpResponse = httpClient.execute(httpPost);
        inputStream = httpResponse.getEntity().getContent();
        if(inputStream!=null)
            result = inputStreamParaString(inputStream);
        else
            result = K.FALHA;
    }catch(UnsupportedEncodingException e){
        e.printStackTrace();
    }catch(ClientProtocolException e){
        e.printStackTrace();
    }catch(IOException e){
        e.printStackTrace();
    }       
    return result;
}

WebService in JAVA

@Path("/enviarFeedBack/")
@POST
@Produces("application/json ; charset=UTF-8")
public String receberFeedBack(String json){
    Feedback fb = new Gson().fromJson(json,Feedback.class);
    fb.setData(new Date());
    Integer result = 
            new FeedbackController().inserir(fb);

    if(result == null || result<0 )
        return K.FALHA;
    else
        return K.SUCESSO;
}

In short, in PHP I do not know the correct way to receive the data via POST that was sent by Android already tried to go through the array $_POST but I do not know if this is correct, and I am also not able to send that response back success or failure.

    
asked by anonymous 22.01.2015 / 18:17

2 answers

3

Webservice receives data via POST from any client.

webservice php

//Recebe dados do cliente.
//Lê o json diretamente dos dados enviados no POST (input)
$json = file_get_contents('php://input');

//DECODIFICA JSON PARA OBJETO FEEDBACK
$fb = json_decode($json);
//Seta atributo data do feedback para data atual
$fb->data = date("Y-m-d H:i:s");

//instancia classe que faz acesso ao banco de dados
$dao = new FeedbackDAO();

//salva objeto e    
//envia resposta para cliente
if($dao->salvar($fb)) 
    echo 'sucesso';
else 
    echo 'falha';
    
23.01.2015 / 04:39
0

You were able to resolve on the side of PHP , but did not answer the question itself on the JAVA side:

PERGUNTA: Sending data from android via POST ..

Well ... I'll show you both via POST and via GET:

public class JSONParser {

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

     public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) 
    {

        // Making HTTP request
        try {

            // CHECANDO O TIPO DE REQUISIÇÃO
            if(method == "POST"){
                // SE A REQUISIÇÃO DO MÉTODO É POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

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

            }else if(method == "GET"){
                // SE A REQUISIÇÃO DO MÉTODO É 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 Error", "Error converting result " + e.toString());
        }

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

        // return JSON String
        return jObj;

    }

}

I HOPE TO HELP SOMETHING:)

    
25.01.2015 / 01:02