4.2

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

打码量(行):350

博客量(篇):1

了解到知识点:学习Client端代码编写

 

 import android.os.AsyncTask;

import android.os.Bundle;

import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.net.HttpURLConnection;

import java.net.URL;

 

public class MainActivity extends AppCompatActivity {

 

    private static final String TAG = "MainActivity";

    private static final String SERVER_URL = "http://your_server_address/api/data"; // 替换为实际服务器地址

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

 

        // 示例:执行网络请求

        new SendDataTask().execute("Hello from client");

    }

 

    private class SendDataTask extends AsyncTask<String, Void, String> {

 

        @Override

        protected String doInBackground(String... params) {

            String response = "";

 

            try {

                URL url = new URL(SERVER_URL);

                HttpURLConnection conn = (HttpURLConnection) url.openConnection();

                conn.setRequestMethod("POST");

                conn.setRequestProperty("Content-Type", "text/plain");

                conn.setDoOutput(true);

 

                // 发送数据

                String input = params[0];

                OutputStream os = conn.getOutputStream();

                os.write(input.getBytes());

                os.flush();

 

                // 获取响应

                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));

                String line;

                while ((line = br.readLine()) != null) {

                    response += line;

                }

 

                // 关闭资源

                br.close();

                os.close();

                conn.disconnect();

 

            } catch (IOException e) {

                e.printStackTrace();

            }

 

            return response;

        }

 

        @Override

        protected void onPostExecute(String result) {

            // 处理服务器响应

            Log.d(TAG, "Server response: " + result);

        }

    }

}

posted @ 2024-04-02 09:55  赵千万  阅读(5)  评论(0编辑  收藏  举报