簡體   English   中英

Android中的OkHttpClient

[英]OkHttpClient in 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();
    }


}

通常錯誤是因為:

  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()); } } } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM