2012-03-08 3 views
0

URL에서 간단한 문자열을 얻는 방법을 정확하게 파악할 수 없습니다. 이 코드의 여러 버전을 시도했습니다 :Android에서 HTML/PHP 문자열 가져 오기

String str = null; 
    try { 
     // Create a URL for the desired page 
     URL url = new URL("mysite.com/thefile.txt"); 

     // Read all the text returned by the server 
     BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); 

     while ((str = in.readLine()) != null) { 
      // str is one line of text; readLine() strips the newline character(s) 
     } 
     in.close(); 
    } catch (MalformedURLException e) { 
    } catch (IOException e) { 
    } 
    Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show(); 

모든 적절한 매니페스트 사용 권한이 있지만 아무 것도 반환 할 수 없습니다. 내 txt 파일은

www.google.com

를 포함하고 난 어떤 브라우저에서 전화 나 컴퓨터에서 액세스 할 수 있습니다. 어떤 아이디어?

답변

0

나는 대답을 찾았습니다 here. 내가 이클립스 날 컴파일 못하게 캐치를 제거하면

Use the DefaultHttpClient httpclient = new DefaultHttpClient(); 

HttpGet httppost = new HttpGet("http://www.urlOfThePageYouWantToRead.nl/text.txt"); 
HttpResponse response = httpclient.execute(httppost); 
     HttpEntity ht = response.getEntity(); 

     BufferedHttpEntity buf = new BufferedHttpEntity(ht); 

     InputStream is = buf.getContent(); 


     BufferedReader r = new BufferedReader(new InputStreamReader(is)); 

     StringBuilder total = new StringBuilder(); 
     String line; 
     while ((line = r.readLine()) != null) { 
      total.append(line + "\n"); 
     } 

     TextView.setText(total); 
2

나는 코드를 보면이, 무엇이 잘못되었는지를 알려하지 않는 놀라지 아니에요 : 오류가 발생

} catch (MalformedURLException e) { 
} catch (IOException e) { 
} 

경우, 당신은 아무것도 통지하지 않습니다. 단지 catch 개의 논문에 오류보고를하고 로그를보십시오. 덧붙여서 mysite.com/thefile.txt은 URL이 아니며 http://mysite.com/thefile.txt은 URL이 아닙니다.

+0

, 그냥 시도 캐치로 둘러싸거나 마침내 시도 /를하려고하면이 같은 것을하지 말한다 : 여기

는 코드입니다. – Nick

+0

@Nick : 그렇다면 이러한 오류를 제대로 처리해야합니다. 현재, 당신은 단지 그들을 무시하고 있습니다 *. 어쩌면 오류를 인쇄하고 나간다. –