我是Android新手。在這種方法中,我願意發送一個BEAccident對象以及一些字符串,但服務器拋出一個錯誤。如何通過URLConnection發送多個JSON對象?
公共字符串SendAccident(BEAccident事故,字符串username, 字符串密碼){
JSONObject jsonAccident = new JSONObject();
try {
jsonAccident.put("HasDocuments", accident.getHasDocuments());
jsonAccident.put("ChassisNumber", accident.getChassisNumber());
jsonAccident.put("ContainerNumber", accident.getContainerNumber());
jsonAccident.put("Description", accident.getDescription());
jsonAccident.put("IdTMUser", accident.getIdTMUser());
jsonAccident.put("LicensePlate", accident.getLicensePlate());
jsonAccident.put("LocalDateTime", accident.getLocalDateTime());
} catch (JSONException e1) {
return e1.getMessage();
}
try{
// Set Request parameter
data +="&" + URLEncoder.encode("Username", "UTF-8") + "="+username;
data +="&" + URLEncoder.encode("Password", "UTF-8") + "="+password;
data +="&" + URLEncoder.encode("LoadNumber", "UTF-8") + "="+"LN0003";
data +="&" + URLEncoder.encode("Accident", "UTF-8") + "="+URLEncoder.encode(jsonAccident.toString(), "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader reader = null;
// Send data
try {
URL url = new URL(URL_SEND_ACCIDENT);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(
conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "");
}
// Append Server Response To Content String
Content = sb.toString();
return Content;
} catch (Exception ex) {
Error = ex.getMessage();
return Error;
} finally {
try {
reader.close();
}
catch (Exception ex) {
}
}
}
請告知,如果這是一個使用的URLConnection發送非本地對象的正確途徑。我很感激任何迴應。
您就可以在服務器端的代碼? – 2014-10-16 21:58:19
@NagyVilmos恐怕它不可用。我所知道的是,它在iOS中完美運行。謝謝。 – Jorge 2014-10-16 23:25:05
嘗試替換您的數據+ =「&」+ URLEncoder.encode(「Accident」,「UTF-8」)+「=」+ URLEncoder.encode(jsonAccident.toString(),「UTF-8」);這行是 'data + =「&」+ URLEncoder.encode(「Accident」,「UTF-8」)+「=」+ jsonAccident.toString();' – 2014-10-17 04:28:57