1. 程式人生 > >Android OkHttp Post 方式登入

Android OkHttp Post 方式登入

 使用FormBody 建立表單項

        FormBody body = new FormBody.Builder()
                .add("user","check")
                .add("password","password")
                .build();

        Request request = new Request.Builder()
                .url("https://example.com/api/v1/login")
                .post(body)
                .build();
        OkHttpClient okHttpClient =new OkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "hchatonFailure: 失敗");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, "hchatOnResponse: "+response.body().string());
                //獲取返回的資訊
            }
        });

一開始我使用了MultipartBody,是錯的,我把FromBody和MultipartBody弄錯了。

RequestBody requestBody = new MultipartBody.Builder()
                .addFormDataPart("user","wxb")
                .addFormDataPart("password","hmt12345678")
                .build();

FromBody用於表單提交,而MultipartBody用於檔案上傳