Я работаю над Google App Engine для хранения данных. Мое приложение - это приложение для Android, и я хочу получать данные из стороны хранилища данных GAE. Однако, когда я хочу получать ArrayList в качестве текста JSON, я получаю сообщение «Ошибка: 500 внутренних Server Error ", и я не смог найти решение о том, что я здесь размещаю коды на стороне клиента и сервера;500 Внутренняя ошибка сервера GAE при попытке отправить строку JSON стороне клиента на стороне Android?
стороне сервера
@SuppressWarnings("serial")
public class ReceiveLoc extends HttpServlet{
public static final String USER_ID = "userId";
public static final String USER_LATITUDE = "latitude";
public static final String USER_LONGITUDE = "longitude";
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
String user_id = req.getParameter(USER_ID);
resp.setContentType("application/json");
PrintWriter out = resp.getWriter();
out.println(receiveLoc(user_id));
out.flush();
}
private String receiveLoc(String user_id) {
// TODO Auto-generated method stub
ArrayList<Location> locations = new ArrayList<ReceiveLoc.Location>();
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Filter filterId = new FilterPredicate(USER_ID, Query.FilterOperator.EQUAL,user_id);
Query q = new Query("UserLoc");
q.setFilter(filterId);
PreparedQuery pq = datastore.prepare(q);
for(Entity result: pq.asIterable()){
double latitude = (double) result.getProperty(USER_LATITUDE);
double longitude = (double) result.getProperty(USER_LONGITUDE);
locations.add(Location.newInstance(latitude, longitude));
}
Type type = new TypeToken<ArrayList<Location>>() {}.getType();
Gson gson = new Gson();
String json = gson.toJson(locations,type);
return json;
}static class Location {
double latitude;
double longitude;
public Location(double latitude,double longitude){
this.latitude = latitude;
this.longitude = longitude;
}
public double getLatitude() {
return latitude;
}
public double getLongitude() {
return longitude;
}
public static Location newInstance(double latitude,double longitude){
return new Location(latitude, longitude);
}
}
}
стороне клиента
class ClientAsyncReceiveLoc extends AsyncTask<String,Void,String> {
//This ASYNCTASK class created different from ClientAsync class because in that class,
//locations(double) values are processed.
Activity activity;
//constructor.
public ClientAsyncReceiveLoc(Activity activity) {
this.activity = activity;
}
@Override
protected String doInBackground(String... user_id) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://application-id.appspot.com/" + MainActivity.OPERATION_RECEIVE_LOC);
List<NameValuePair> nameValuePairs = new ArrayList<>(1);
nameValuePairs.add(new BasicNameValuePair(User.USER_ID, user_id[0]));
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
Log.i("Connection Response Code",String.valueOf(response.getStatusLine().getStatusCode()));
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity);
}
return "Error : " + response
.getStatusLine()
.getStatusCode() + " " + response
.getStatusLine().getReasonPhrase();
} catch (MalformedURLException e) {
return e.getMessage();
} catch (UnsupportedEncodingException e) {
return e.getMessage();
} catch (IOException e) {
return e.getMessage();
}
}
@Override
protected void onPostExecute(String jsonResponse) {
//super.onPostExecute(s);
Log.i("RECEIVED",jsonResponse);
}
}
какая ошибка вы получаете? – jirungaray
Я получил точно код ответа как ** 500 Internal Server Error ** на моем экране LogCat, и теперь я решил проблему. Проблема заключается в добавлении библиотеки GSON к моему серверному проекту, я пропустил часть, добавляя файлы .jar. Спасибо @jirungaray за ваш интерес. – user3751548
без проблем, объясняя, как вы решаете свою проблему и закрываете вопрос :) – jirungaray