2014-05-24 113 views
0

我是新来的android和我想连接到json文件,但是当我尝试此代码,但它不连接,当我在我的手机上运行它时,我想工作,它会得到我在logcat的nooo根据我说,当它有问题连接到服务器,谢谢使用android连接到服务器

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; 



} 

} 
+0

ApiException打印到日志是什么?如果什么都没有,请尝试记录异常并发布日志。例如,而不是'Log.d(logTag,“noo !!”);'尝试'Log.d(logTag,e.getMessage());' – katzenhut

+0

我这样做05-25 12:14:37.882 :D/LastFMHelper(22953):权限被拒绝(缺少INTERNET权限?) – amirhtk

回答

0

在AppManifest文件标签 - 在<manifest>顶部添加此行如果你不给我们日志,有很多原因可以预测。我只是预测错了: 也许你必须把这个片段放在服务器请求之前:

if (android.os.Build.VERSION.SDK_INT > 9) { 
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
        StrictMode.setThreadPolicy(policy); 
       } 
+0

问题与互联网权限有关(请参阅问题评论)。但这看起来很有趣。谨慎地阐述一下?这是做什么的? – katzenhut

+0

针对网络访问的StrictMode会导致Android 3.0(Honeycomb)或更高版本发生致命错误,除非您的应用程序针对API版本,然后Honeycomb.t允许在应用程序中设置策略以避免做错事情。例如,如果以下设置违反了某些Android策略,则会导致应用程序崩溃。 StrictMode只能在开发过程中使用,而不能在实时应用程序中使用。 Ref:Vogella –

+0

谢谢。我不知道。 – katzenhut