使用android连接到服务器
我是android新手,我想连接到json文件,但当我尝试这段代码但它不连接时,当我在手机上运行它时,当我想工作时,它会让我在logcat中找到nooo,根据我说的,当它连接到服务器时会这样做,谢谢使用android连接到服务器,android,json,connection,Android,Json,Connection,我是android新手,我想连接到json文件,但当我尝试这段代码但它不连接时,当我在手机上运行它时,当我想工作时,它会让我在logcat中找到nooo,根据我说的,当它连接到服务器时会这样做,谢谢 public class LastFMHelper { public static final String LastFMMetroTrackChartUrl= "http://ws.audioscrobbler.com/2.0/?method=geo.getmetrotrackc
public class LastFMHelper {
public static final String LastFMMetroTrackChartUrl=
"http://ws.audioscrobbler.com/2.0/?method=geo.getmetrotrackchart&country=united+states&metro=denver&format=json&api_key=bc8ae5008414312b31e8c23f684d67cc";
private static final int HTTP_STATUS_OK = 200;
private static byte[] buff = new byte[1024];
private static final String logTag="LastFMHelper";
public static class ApiException extends Exception
{
private static final long serialVersionUID= 1L;
public ApiException (String msg)
{
super(msg);
}
public ApiException(String msg, Throwable thr)
{
super(msg, thr);
}
}
protected static synchronized String downlaodFromServer (String ...params) throws ApiException {
String retval= null;
String metro = params[0];
String url= LastFMMetroTrackChartUrl + "&metro" +metro;
Log.d(logTag,"Fetching"+url);
HttpClient client= new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try{
HttpResponse responce = client.execute(request);
StatusLine status = responce.getStatusLine();
if(status.getStatusCode()!=HTTP_STATUS_OK)
{
throw new ApiException("Invalid responce from last.fm"+status.toString());
}
HttpEntity entity = responce.getEntity();
InputStream ist = entity.getContent();
ByteArrayOutputStream content = new ByteArrayOutputStream();
int readcount =0;
while((readcount= ist.read(buff)) != -1)
{
content.write(buff,0,readcount);
}
retval= new String (content.toByteArray());
}catch(Exception e){
Log.d(logTag,"noo!!");
throw new ApiException("problem connecting to server " + e.getMessage(),e);
}
return retval;
}
}
这是你的问题。您没有internet权限,因此您的应用无法连接到服务器。在AppManifest文件的
-标记顶部添加此行:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
我建议您阅读以下关于AppManifest及其如何处理权限的指南:
如果您不给我们日志,有很多原因是可以预测的。我只是预测错了: 可能您必须将此代码段放在请求服务器之前:
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
ApiException在日志中打印什么?如果没有异常,请尝试记录异常并发布日志。例如,代替
Log.d(logTag,“noo!!”)
tryLog.d(logTag,e.getMessage())代码>我这么做了,它说05-25 12:14:37.882:D/LastFMHelper(22953):权限被拒绝(缺少INTERNET权限?)问题在于INTERNET权限(请参阅对问题的评论)。但这看起来很有趣。想详细说明一下吗?这有什么作用?StrictMode for network access会导致与Android 3.0(蜂巢)或更高版本相同的致命错误,除非您的应用程序针对的是蜂巢之前的API版本。t允许在应用程序中设置策略以避免执行错误操作。例如,如果以下设置违反了某些Android策略,则会导致应用程序崩溃。StrictMode只应在开发过程中使用,而不应在实时应用程序中使用。参考:沃格拉