我正在尝试通过异步任务发布到服务器,并在将Hashmap转换为String时发生此错误。这个错误是什么意思。它为什么会出现?我该如何解决这个问题? 这是我的代码:
public class NetworkAccess extends AsyncTask<HashMap<String,String>,Void,String> {
private URL url;
private HttpURLConnection con;
private OutputStream os;
@Override
protected String doInBackground(HashMap<String, String>... vals) {
String response = "";
try {
url = new URL("http://192.168.0.3/chow/user-login.php");
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setConnectTimeout(1000);
OutputStream os = con.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
String pd = getPostDataString(vals); //Error
writer.write(pd);
writer.flush();
writer.close();
BufferedInputStream bis = new BufferedInputStream(con.getInputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(bis));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
response = total.toString();
}
catch (Exception e){
e.printStackTrace();
return response;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}
答案 0 :(得分:0)
你得到的错误表明你直接尝试创建一个HashMap数组,而不是只创建String of String,迭代Collection并将HashMap对象插入其中。
在getPostDataString()内,将代码更改为
StringBuilder [] sb = new StringBuilder [100];
并检查它是否有效。