1. 程式人生 > >Android OKhttp請求遇到的問題

Android OKhttp請求遇到的問題

剛開始學習Android網路請求記錄一下

  1. OKhttp提示錯誤android.os.NetworkOnMainThreadException看意思就是不能再主執行緒中寫。
  2. 提示not permitted by network security poliy 看意思跟iOS裡面的策略差不多,iOS使用http請求需要設定一下安全策略,可是我這是百度HTTPS啊,參考文章解決辦法
public class NetWorkACT extends AppCompatActivity {

    final private static String TAG = "log";
    private Button button;
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle bundle = msg.getData();
            String value = bundle.getString("value");
            Log.i(TAG,"請求結果"+value);
        }
    };
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            OkHttpClient okHttpClient = new OkHttpClient();
            String string = "https://www.baidu.com";
            Request request = new Request.Builder().url(string).build();
            try {
                Response response = okHttpClient.newCall(request).execute();
                String res = response.body().toString();
                System.out.println(res);
                Message message = new Message();
                Bundle bundle = new Bundle();
                bundle.putString("value",res);
                message.setData(bundle);
                handler.sendMessage(message);
            } catch (IOException exception){

            }

        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_net_work_act);
//        if (android.os.Build.VERSION.SDK_INT > 9) {
//            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
//            StrictMode.setThreadPolicy(policy);
//        }


        button = (Button)findViewById(R.id.start);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startRequest();
//                OkHttpClient okHttpClient = new OkHttpClient();
//                String string = "https://www.baidu.com";
//                Request request = new Request.Builder().url(string).build();
//                try {
//                    Response response = okHttpClient.newCall(request).execute();
//                    String res = response.body().toString();
//                    System.out.println("請求介面"+res);
//                    Message message = new Message();
//                    Bundle bundle = new Bundle();
//                    bundle.putString("value",res);
//                    message.setData(bundle);
//                    handler.sendMessage(message);
//                } catch (IOException exception){
//
//                }
            }
        });
    }
    private void startRequest() {
        new Thread(runnable).start();
    }
}