0

I need to send this data via POST method to a PHP page I have tried several examples but without any joy can anyone please give me a simple example of it.

I can send it via GET method successfully.

String serial = android.os.Build.SERIAL;
String board = android.os.Build.BOARD;
String display = android.os.Build.DISPLAY;
String model = Build.MODEL;
String id = android.os.Build.ID;
String manufacturer = Build.MANUFACTURER;
String brand = Build.BRAND;
String type = Build.TYPE;
String user = Build.USER;
String base = "" + android.os.Build.VERSION_CODES.BASE;
String incremental = android.os.Build.VERSION.INCREMENTAL;
String sdk = android.os.Build.VERSION.SDK;
String host = Build.HOST;
String fingerprint = Build.FINGERPRINT;
String versionCode = Build.VERSION.RELEASE;

android.content.Intent intent = new android.content.Intent(android.content.Intent.ACTION_VIEW,
android.net.Uri.parse("http://xxxxxxxxxxxx/?Serial="+serial+"&Board="+board+"" +
        "&Display="+display+"&Model="+model+"&Id="+id+"&Manufacture="+manufacturer+"&Brand="+brand+"" +
        "&Type="+type+"&User="+user+"&Base="+base+"&Incremental="+incremental+"&SDK="+sdk+"" +
        "&Host="+host+"&Fingerprint="+fingerprint+"&VersionCode="+versionCode));
startActivity(intent);
3

1 Answer 1

1

You can use Android's HttpURLConnection class for that. Following is the method to make that request with parameters.

// Create Post Request
public String makePostRequest(String requestURL, String params) {

    String text = "";
    BufferedReader reader = null;

    // Send data
    try {
        // Defined URL  where to send data
        URL url = new URL(requestURL);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Accept", "*/*");

        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(params);
        wr.flush();

        // Get the server response

        reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;

        // Read Server Response
        while ((line = reader.readLine()) != null) {
            // Append server response in string
            sb.append(line + "\n");
        }

        text = sb.toString();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            reader.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    // Show response on activity
    return text;
}

The parameters passed to this method should be encoded in order to avoid any inconvenience due to special characters. Following is the method to encode parameters

public String encodeParams(HashMap<String, String> params) throws UnsupportedEncodingException {
    String encodedParams = "";
    /* Display content using Iterator*/
    Set set = params.entrySet();
    Iterator iterator = set.iterator();
    while (iterator.hasNext()) {
        if (encodedParams != null && !encodedParams.equals("")))
            encodedParams += "&";
        Map.Entry mentry = (Map.Entry) iterator.next();
        encodedParams += URLEncoder.encode(mentry.getKey().toString(), "UTF-8")
                + "=" + URLEncoder.encode(mentry.getValue().toString(), "UTF-8");
    }
    return encodedParams;
}

In order to make Http Request, call these methods as follows:

try {
            // prepare parameters for http call
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("serial", android.os.Build.SERIAL);
            hashMap.put("board", android.os.Build.BOARD);

            // encode parameters
            String encodedParams = encodeParams(hashMap);
            // create request url
            String requestUrl = "http://xxxxxxxxxxxx/"; // your URL
            // make a post request to server with request url create above
            String response = makePostRequest(requestUrl, encodedParams, null);
            return response;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

P.S. you should try running this code using background thread or AsyncTask for better performance avoiding NetworkOnMainThread exception.

Sign up to request clarification or add additional context in comments.

8 Comments

@Tony does this answer help your query?
Thanks for your reply, requestUrl and encodedParams has value as expected but 'response' is always empty why ? what am I doing wrong ?
have you already tested your server? please use hurl.it to verify if your server is returning the correct result
have you tried to debug the encoded params string and other strings for if they have valid values?
Do I need to change anything in 'makePostRequest()' method ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.