[英]Calling REST Web Services in Android and getting null in String data
我試圖通過傳遞lat和lon以及userID來調用帶有sampleURL的REST Web服務。 但是我總是在String數據中得到null
。 有什么建議為什么會發生嗎? 我正在使用Android。 但是,當我嘗試在瀏覽器中打開該URL時,它將被打開,並且可以看到響應。 我猜我的代碼有問題。
private class GPSLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location location) {
if (location != null) {
GeoPoint point = new GeoPoint(
(int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6));
String data = findUsersInCurrentRadius(1,location.getLatitude(),location.getLongitude());
System.out.println("Got Data" +data);
textView.setText(data);
}
private String findUsersInCurrentRadius(int userid, double lat, double lon) {
String sampleURL = SERVICE_URL + "/"+REMOTE_METHOD_NAME+"/"+userid+"/"+lat+"/"+lon;
System.out.println(sampleURL);
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(sampleURL);
String text = null;
try {
HttpResponse response = httpClient.execute(httpGet, localContext);
System.out.println("Some Response" +response);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e1) {
return e1.getLocalizedMessage();
}
return text;
}
}
您正在主UI線程上運行網絡請求。 使用AsyncTask執行網絡請求。 Android OS> = 3.0不允許在主UI線程上運行網絡請求。
你可以像這樣使用AsyncTask
private class NetworkRequest extends AsyncTask<String, Void, String> {
int userid;
double lat, lon;
String reponse;
public NetworkRequest(int userID, double lat, double lon) {
this.userid = userID;
this.lon = lon;
this.lat = lot;
}
@Override
protected String doInBackground(String... params) {
reponse = findUsersInCurrentRadius(userid, lat, lon);
return "Executed";
}
@Override
protected void onPostExecute(String result) {
if (null != reponse) {
System.out.println("Got Data" + reponse);
textView.setText(reponse);
}
else{
//Handle the Error
}
}
}
然后在您的onLocationChanged
調用Async Task
new NetworkRequest(userid,lat,lon).execute();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.