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

你可能感兴趣的:(Android)