I'm using an HttpsURLConnection to connect to an application. Everything is fine until I'm trying to use parameters (like username and password) in the request due to the fact that on server side null values are mapped to parameters.
HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
connection.addRequestProperty("password", "xxxx");
connection.addRequestProperty("username", "aaaaaa");
connection.addRequestProperty("eventId","btnLogin");
connection.setRequestMethod("POST"); //$NON-NLS-1$
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty( "Accept", "*/*" );
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
I mention that HttpsURLConnection works and the initial login page is retrieved via HttpsUrlConnection.
How can I send successfully the parameters on the server side via a POST request?
I order to solve the issue I have created a Map reference to a HashMap object on which I have stored in the keys the parameters and in the values the values for those parameters.
After that I have created a method that will return a String object containing the encoded paramters to be used for a POST request.
private String getOutput(Map<String, String> hm) throws UnsupportedEncodingException {
String out = "";
boolean start = true;
for(Map.Entry<String, String> h : hm.entrySet()){
if(start){
start=false;
out+=URLEncoder.encode(h.getKey(), "UTF-8");
out+="=";
out+=URLEncoder.encode(h.getValue(), "UTF-8");
}
else{
out += "&";
out+=URLEncoder.encode(h.getKey(), "UTF-8");
out+="=";
out+=URLEncoder.encode(h.getValue(), "UTF-8");
}
}
All of the above were used in an output stream in order to send them to the server.
out = new BufferedWriter(
new OutputStreamWriter(connection.getOutputStream())
);
out.write(getOutput(hm));
out.close();