2015-10-02 93 views
0

我寫了下面的代碼發送一個請求到服務器並從服務器獲取響應。但是,當我運行下面的代碼它不能爲我工作。我寫了這個代碼爲this linkOkHttpClient在android

public class MainActivity extends Activity { 
    @Override 
    protected void onCreate(Bundle bundle) { 
     super.onCreate(bundle); 
     setContentView(R.layout.activity); 
     Button button = (Button)findViewById(R.id.bu1); 
     button.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       try { 
        run(); 
       } catch (Exception e) { 
       Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show(); 
       } 
      } 
     }); 
    } 
    private final OkHttpClient client = new OkHttpClient(); 
    public void run() throws Exception { 
     Request request = new Request.Builder() 
       .url("http://127.0.0.1:8080/file.php") 
       .build(); 

     Call call = client.newCall(request); 
     Response response = call.execute(); 

     if (!response.isSuccessful()) { 
      throw new IOException("Unexpected code " + response); 
     } 
     String text = response.body().string(); 
     Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show(); 
    } 


} 
+0

什麼錯誤。請發佈一些logcat。 – Tauqir

+1

什麼不適合你?請向我們顯示您有互聯網許可的錯誤 – bashoogzaad

+0

?) – ligi

回答

0

通常的錯誤是因爲:

  1. 沒有Internet的權限

  2. 它是在UI線程

可以確認在logcat的。

解決方案:

  1. 加入清單中<uses-permission android:name="android.permission.INTERNET" />
  2. 您必須在其它線程中運行或使用異步一個這樣的:

    public void run() { 
        Request request = new Request.Builder() 
          .url("http://127.0.0.1:8080/file.php") 
          .build(); 
    
        Call call = client.newCall(request); 
        call.enqueue(new Callback() { 
         @Override 
         public void onFailure(Request request, IOException e) { 
          Log.d("TAG", "Failed: " + e.getMessage()); 
         } 
    
         @Override 
         public void onResponse(Response response) throws IOException { 
          Log.d("TAG", "OK: " + response.body().string()); 
         } 
        } 
    } 
    
相關問題