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

Asked

Viewed 3,188 times

4

I had made a webservice in java, now I’m switching to PHP and I’m having difficulty 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 do not know the correct way to receive the data via POST that were sent by Android already tried to go through the array $_POST but I don’t know if that’s right, and I’m also not getting to send that answer back success or failure.

  • 6

    Take a look at this answer: http://answall.com/a/46958/20594

  • 1

    Tries to change the Content-type android application/json for application/x-www-form-urlencoded if all goes well you should receive in the variable $_POST

  • @Icaromartins tried the way Voce mentioned and it did not work. You have already used this solution successfully?

  • 1

    @Andréribeiro Oce solved, I had not seen that other topic, so I will put the solution together with the question and you copy and glue as an answer. This is if not closed by doubling the question. It has mt in common with the other. Thank you

  • @Juarez Glad you solved it! You can take the PHP code you made, answer your question and mark as accepted. It is very similar to the other but do not believe it is duplicated. Note: in your case there is no need to set these headers.

2 answers

2


Webservice receives data via POST from any customer.

php webservice

//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';
  • If your answer may be valid you should give a small description of what you did. A response just posting the code has very low quality.

0

You managed to settle on the side of PHP, but did not answer the question itself from the side JAVA:

PERGUNTA: Sending android data 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 IT HELPS SOMETHING :)

  • It works, my friend, but the request is not POST

  • @Juarez, when you understand the difference between your question and your solution, come back here and give me +1.

Browser other questions tagged

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