我试图通过UrlEncoding从android发送到post页面的变量,如果我只发送一个变量,这对我有效。那么如何编码多个变量,我自己尝试了一些。
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();
这是在做这项工作,但只有第一个变量可以通过php端访问。
答案 0 :(得分:2)
您只能访问第一个变量,因为您没有使用&
附加每个参数。您可以使用此方法获取参数字符串。
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();
}
您可以获得如下参数字符串:
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);
答案 1 :(得分:0)
试试这个:
wr.write(data);
wr.flush();
wr.write(data1);
wr.flush();
wr.write(data2);
wr.flush();
wr.write(data3);
wr.flush();