用OkHttp实现网络请求

post方法:

public class TestOKHttpActivity extends AppCompatActivity {
    String baseurl = "http://haitao3.isudoo.com/index.php/Service";
    String codeApi = "/api/validateCode";
    String registApi = "/api/signup";
    String loginApi = "/api/signin";

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_okhttp);
        Button btnSend = (Button) findViewById(R.id.btnSend);
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // testPostOkHttp("/api/validateCode");
                new Thread(runnable).start();
            }
        });
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            OkHttpClient client = new OkHttpClient();
            RequestBody formBody = new FormEncodingBuilder()
                    .add("username", "15606526783")
                    .add("password","123456")
                    .build();
            Request request = new Request.Builder()
                    .url(baseurl + loginApi)
                    .post(formBody)
                    .build();
            Response response = null;
            try {
                response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    //Toast.makeText(this, "success", Toast.LENGTH_SHORT).show();
                    Log.i("msg", response.body().string() + "++++++++++++++++++++++++--------------------------------***");
                } else {
                    //throw new IOException("Unexpected code " + response);
                    //Toast.makeText(this, response+"*", Toast.LENGTH_SHORT).show();
                    Log.i("msg", "failssssss++++++++++++++++++++++++--------------------------------***");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };
}

你可能感兴趣的:(Android)