2

I am trying to use the tutorial here with the data I learned here to perform a HTTPUrlConnection POST Request. Every time I run it, the response gives the error message: "You Must enter a user name!" and "You must enter a password." Could anyone please explain why the server is not recognizing or even getting the posted data? Here is my code:

class urlRequest extends AsyncTask<String, String, String> {

protected String doInBackground(String... all) {
            URL url;
            String response = "";
            try {
                String requestURL = "https://hac.chicousd.org/LoginParent.aspx?page=GradebookSummary.aspx";
                url = new URL(requestURL);

                HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
                conn.setReadTimeout(15000);
                conn.setConnectTimeout(15000);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
                conn.setRequestProperty( "charset", "utf-8");
                conn.setRequestProperty( "Content-Length", Integer.toString(getPostDataString(postDataParams).length()));
                conn.setFixedLengthStreamingMode(getPostDataString(postDataParams).length());


                JSONObject postDataParams = new JSONObject();
                postDataParams.put("checkCookiesEnabled", "true");
                postDataParams.put("checkMobileDevice", "false");
                postDataParams.put("checkStandaloneMode", "false");
                postDataParams.put("checkTabletDevice", "false");
                postDataParams.put("portalAccountUsername", "username");
                postDataParams.put("portalAccountPassword", "password");

                DataOutputStream os = new DataOutputStream(conn.getOutputStream());
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));

                writer.write(getPostDataString(postDataParams)); // returns: checkCookiesEnabled=true&checkMobileDevice=false&checkStandaloneMode=false&checkTabletDevice=false&portalAccountUsername=username&portalAccountPassword=password

                writer.close();
                os.close();

                int responseCode=conn.getResponseCode();

                if (responseCode == HttpsURLConnection.HTTP_OK) {
                    String line;
                    BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    while ((line=br.readLine()) != null) {
                        response+=line;
                        Log.i("tag", line);
                    }
                }
                else {
                    response="";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
    return response;
           }

public String getPostDataString(JSONObject params) throws Exception {

    StringBuilder result = new StringBuilder();
    boolean first = true;

    Iterator<String> itr = params.keys();

    while(itr.hasNext()){

        String key= itr.next();
        Object value = params.get(key);

        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(key, "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(value.toString(), "UTF-8"));

    }
    return result.toString();
}
Community
  • 1
  • 1
Jacolack
  • 1,365
  • 2
  • 11
  • 25

2 Answers2

0

Posting parameters Using POST:-

URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream  input;
url = new URL (getCodeBase().toString() + "env.tcgi");
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");   
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();  
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("portalAccountUsername", "username");
jsonParam.put("portalAccountPassword", "password");

The part which you missed is in the the following... i.e., as follows..

// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.writeBytes(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
printout.flush ();
printout.close ();
siddhesh
  • 563
  • 1
  • 9
  • 15
  • I changed the writer.write to printout.writeBytes like you showed, and no change. But then I added the urlConn.setRequestProperty("Host", "android.schoolportal.gr"); and no response was printed. Explanation? – Jacolack Jan 02 '17 at 06:09
  • and could you explain: (getCodeBase().toString() + "env.tcgi") and "android.schoolportal.gr" – Jacolack Jan 02 '17 at 06:12
  • the url part and host part dont use it i have use it for my purpose . I had just copied my code block and posted it here just ignore that part – siddhesh Jan 02 '17 at 06:14
  • ok than the main part of your answer (printout part) does not work... it seems like every attempt at writing the post doesn't get through and it just receives the response as if it never posted anything at all (lacking username and password) any idea on ensuring the JSON data is sent with the request? – Jacolack Jan 02 '17 at 06:18
0

u are got message from validation so please check username and password not null or blank before use it.

Anil Kanani
  • 260
  • 2
  • 19