Skip to content Skip to sidebar Skip to footer

How To Send Url Paremeters To Php Server And Get Back Response To Android

I'm trying to create a basic application where I want to send a request from android to php server like this: http://www.eg.com/eg.php?a=blabla:blablabla:bla. Then when i get this

Solution 1:

I have finally found a simple solution with the help of the comments and hours of research:

You can simple call this method by using this:

HashMap<String , String> postDataParams = newHashMap<String, String>();

postDataParams.put("name", "value");

performPostCall("URL", postDataParams);

Java code:

publicStringperformPostCall(String requestURL,
                                   HashMap<String, String> postDataParams) {

        URL url;
        String response = "";
        try {
            url = newURL(requestURL);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);


            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = newBufferedWriter(
                    newOutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));

            writer.flush();
            writer.close();
            os.close();
            int responseCode=conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {
                String line;
                BufferedReader br=newBufferedReader(newInputStreamReader(conn.getInputStream()));
                while ((line=br.readLine()) != null) {
                    response+=line;

                    Log.e("Res:", response);
                }
            }
            else {
                response="";

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return response;
    }

    privateStringgetPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
        StringBuilder result = newStringBuilder();
        boolean first = true;
        for(Map.Entry<String, String> entry : params.entrySet()){
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        return result.toString();
    }

On the php side you can get the data by using:

$_POST['name']

you can send back response by simply doing this:

echo"response here..";

Post a Comment for "How To Send Url Paremeters To Php Server And Get Back Response To Android"