2013-12-02 1 views
4

몇 가지 포럼 게시물을 살펴본 결과 내 문제에 대한 답을 찾을 수 없습니다. 나는 PHP 파일에서 응답을 얻으려고 노력하고 있습니다. PHP 파일이 작동 중입니다. 문제는 Android 앱이 내 요청을 실행하지 않는다는 것입니다.Android HTTP 받기

public void changText(View view) { 
    TextView textv = (TextView)findViewById(R.id.textview1); 
    textv.setText("Text Has Been Changed"); 
    BufferedReader in = null; 
    String data = null; 

    try{ 
      HttpClient httpclient = new DefaultHttpClient(); 

      HttpGet request = new HttpGet(); 
      URI website = new URI("http://alanhardin.comyr.com/matt24/matt28.php"); 
      request.setURI(website); 
      HttpResponse response = httpclient.execute(request); 
      in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 

      textv.append(" Connected "); 
     }catch(Exception e){ 
      Log.e("log_tag", "Error in http connection "+e.toString()); 
     } 


    } 

텍스트 뷰 읽기 : 여기가 텍스트 뷰에서 얻을 내 코드와 결과의 두 가지 예는 텍스트

을 변경되었습니다
public void changText(View view) { 
    TextView textv = (TextView)findViewById(R.id.textview1); 
    textv.setText("Text Has Been Changed"); 
    BufferedReader in = null; 
    String data = null; 

    try{ 
      HttpClient httpclient = new DefaultHttpClient(); 

      HttpGet request = new HttpGet(); 
      URI website = new URI("http://alanhardin.comyr.com/matt24/matt28.php"); 
      request.setURI(website); 
      //HttpResponse response = httpclient.execute(request); 
      //in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 

      textv.append(" Connected "); 
     }catch(Exception e){ 
      Log.e("log_tag", "Error in http connection "+e.toString()); 
     } 


    } 

텍스트 뷰 읽기 : 텍스트가 연결 변경되었습니다

이 매니페스트에 :

<uses-permission android:name="android.permission.INTERNET" /> 

오류 로그에 다음과 같은 메시지가 표시됩니다. ing : http 연결에 오류가 있습니다. android.os.NetworkOnMainThreadException

어떤 도움을 주시면 감사하겠습니다.

+0

게시 한 코드에는 독자를 구성한 후에 실제로 데이터를 읽지 않습니다. –

+1

코드를 실행하면 어떻게됩니까? – Megamind

+0

반환 된 JSON 객체를 읽으려고하지 않고 있습니다. PHP 파일에 연결하려고합니다. – user908759

답변

12

Android가 요청한 내용을 처리하고 있습니다. 서버에서 반환 한 데이터를 무시하는 것 같습니다. 당신은 예를 들어, 다음과 같이 뭔가를 할 수 :

public void changText(View view) { 
    TextView textv = (TextView)findViewById(R.id.textview1); 
    textv.setText("Text Has Been Changed"); 
    BufferedReader in = null; 
    String data = null; 

    try{ 
      HttpClient httpclient = new DefaultHttpClient(); 

      HttpGet request = new HttpGet(); 
      URI website = new URI("http://alanhardin.comyr.com/matt24/matt28.php"); 
      request.setURI(website); 
      HttpResponse response = httpclient.execute(request); 
      in = new BufferedReader(new InputStreamReader(
        response.getEntity().getContent())); 

      // NEW CODE 
      String line = in.readLine(); 
      textv.append(" First line: " + line); 
      // END OF NEW CODE 

      textv.append(" Connected "); 
     }catch(Exception e){ 
      Log.e("log_tag", "Error in http connection "+e.toString()); 
     } 
} 

서버는 JSON 객체를 반환처럼 보이는, 그래서 당신은 아마, 전체 응답을 읽을 등보다 지능적인 일을 구문 분석 할 것 (new JSONArray(response)를 사용하여), 관련 필드를 추출 할 수 있지만 위의 코드는 적어도 Android가 쿼리를 실행하는지 확인합니다.

EDIT :보고 한 예외 상황에서 코드가 기본 UI 스레드에서 실행되고있는 것처럼 보입니다. API 11 현재 금지되어 있습니다 (그리고 그 전에 frowned되었습니다). 이 문제를 해결하는 방법에 대한 몇 가지 기사가 있습니다. 안내문 Painless threading과 자습서 herehere을 참조하십시오. 자세한 내용은 this thread을 참조하십시오.

+0

전체 응답을'String'으로 읽으려면 [이 답변]을보십시오 (http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string/5445161#5445161).). –

+0

답변 해 주셔서 감사합니다. 불행히도 새 코드가 작동하지 않습니다. TextView는 여전히 "Text Has Been Changed"라고 읽습니다. 문제는 JSON 구문 분석이 아니라 httpclient.execute (요청)와 관련이있는 것으로 보입니다. 결국 JSON 객체를 읽어야 할 것입니다.하지만 지금은 PHP 파일에 연결하려고합니다. – user908759

+0

@ user908759 - 여전히 "연결됨"이라는 단어가 추가됩니까? 아마 당신은 지금 예외를 잡기 중이다. (그런데'e.toString()'을 호출하는 대신에 세 개의 인자를 가진 호출'Log.e ("log_tag", "Error in http connection", e);를 사용하여 예외를 로그하는 것이 더 낫다. logcat에서 더 많은 정보를 얻을 수 있습니다.) –

0
private InputStream downloadUrl(final URL url) throws IOException { 
    HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
    conn.setReadTimeout(NET_READ_TIMEOUT_MILLIS /* milliseconds */); 
    conn.setConnectTimeout(NET_CONNECT_TIMEOUT_MILLIS /* milliseconds */); 
    conn.setRequestMethod("GET"); 
    conn.setDoInput(true); 
    // Starts the query 
    conn.connect(); 
    return conn.getInputStream(); 
}