6.6

所花时间(包括上课):2

打码量(行):220

博客量(篇):1

了解到知识点:学习post请求

 

package com.example.myapp;

 

import android.os.Bundle;

import android.util.Log;

 

import androidx.appcompat.app.AppCompatActivity;

 

import okhttp3.Call;

import okhttp3.Callback;

import okhttp3.FormBody;

import okhttp3.OkHttpClient;

import okhttp3.Request;

import okhttp3.RequestBody;

import okhttp3.Response;

 

import java.io.IOException;

 

public class MainActivity extends AppCompatActivity {

 

    private static final String TAG = "MainActivity";

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

 

        // 示例代码:发送 POST 请求

        sendPostRequest();

    }

 

    private void sendPostRequest() {

        OkHttpClient client = new OkHttpClient();

 

        // 准备请求体,这里示范发送一个简单的表单请求

        RequestBody formBody = new FormBody.Builder()

                .add("username", "john_doe")

                .add("password", "password123")

                .build();

 

        // 创建 POST 请求

        Request request = new Request.Builder()

                .url("http://api.example.com/post_endpoint")

                .post(formBody)

                .build();

 

        // 异步发送请求

        client.newCall(request).enqueue(new Callback() {

            @Override

            public void onResponse(Call call, Response response) throws IOException {

                if (response.isSuccessful()) {

                    String responseData = response.body().string();

                    Log.d(TAG, "Response: " + responseData);

                    // 处理响应数据

                } else {

                    // 请求失败

                    Log.e(TAG, "Request failed");

                }

            }

 

            @Override

            public void onFailure(Call call, IOException e) {

                // 网络请求失败

                e.printStackTrace();

            }

        });

    }

}

posted @ 2024-06-06 18:35  赵千万  阅读(3)  评论(0编辑  收藏  举报