Java 在Android中调用REST Web服务并获取字符串数据中的null
我试图通过传递lat、lon和userID,用sampleURL调用RESTWeb服务。但是我总是在字符串数据中得到Java 在Android中调用REST Web服务并获取字符串数据中的null,java,android,web-services,rest,Java,Android,Web Services,Rest,我试图通过传递lat、lon和userID,用sampleURL调用RESTWeb服务。但是我总是在字符串数据中得到null。有什么建议说明为什么会这样吗?我在用安卓。但当我试图在浏览器中打开该url时,它会被打开,我可以看到响应。我想我的代码有问题 private class GPSLocationListener implements LocationListener { @Override public void onLocationChanged(Location loc
null
。有什么建议说明为什么会这样吗?我在用安卓。但当我试图在浏览器中打开该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
}
}
}
您是否检查了您的
HttpResponse
的状态代码?如果您在请求设置中犯了一个小错误怎么办?您正在测试哪个android OS
?顺便说一句,响应
为空或文本
为空?字符串数据在我上面的代码中为空。为了让大家清楚,这是上面用于调用REST Web服务并从中获取数据的完整代码。您正在主UI线程上运行网络请求。使用AsyncTask
执行网络请求。Android OS>3.0不允许在主UI线程上运行Network request
。我该怎么做。你能给我看一个关于我代码的例子吗。这样我就能理解这件事了。
new NetworkRequest(userid,lat,lon).execute();