I'm trying to send post variables through UrlEncoding from android to php page which is working for me if i send one variable only. So how to encode more than one variable, i've tried some on my own.
protected String doInBackground(String... params) {
try {
String link = "http://URL.php";
String name = params[0];
String email = params[1];
String phone = params[2];
String pass = params[3];
String data = URLEncoder.encode("phone", "UTF-8") + "=" + URLEncoder.encode(phone, "UTF-8");
String data1 = URLEncoder.encode("email", "UTF-8")+ "=" + URLEncoder.encode(email, "UTF-8");
String data2 = URLEncoder.encode("name", "UTF-8")+ "=" + URLEncoder.encode(name, "UTF-8");
String data3 = URLEncoder.encode("pass", "UTF-8")+ "=" + URLEncoder.encode(pass, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.write(data1);
wr.write(data2);
wr.write(data3);
wr.flush();
This is doing the job but only first variable is accessible through php side.
You're only able to access the first variable because, you are not appending each parameter with &
. You could use this method to get a parameter string.
public String getPostDataString(HashMap<String, String> params){
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
try {
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return result.toString();
}
You can get a parameter string like this:
HashMap<String, String> params = new HashMap<>();
params.put("phone",phone);
params.put("email",email);
params.put("name",name);
params.put("pass",pass);
String paramString = getPostDataString(params);