android stdio 做HttpClient客户端,发送post请求附加键值

一、前言

本文实现内容为android作为http客户端,esp32作为http服务端,实现手机控制舵机开关灯。
esp32详见:esp32 做 HttpServer服务器,接收客户端请求

二、代码实现

package com.example.locallock;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    private static String TAG = "MainActivity";
    private String sendurl = "http://192.168.1.100:80/set";
    private Button but_open;
    private Button but_close;
    private Dialog mDialog;

    Handler handler = new Handler();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        but_close = findViewById(R.id.but_close);
        but_open = findViewById(R.id.but_open);

        but_open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("打开");
                mDialog = DialogUtil.createLoadingDialog(MainActivity.this, "正在更改设置...");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        int val = 0;
                        String reply = LoginOfPost(sendurl, "&val=0");
                        System.out.println("服务器返回:" + reply);
                        if (reply == null) {
                            showToast("设置失败,请检查网络!!");
                        } else {
                            showToast("设置成功!!");
                        }
                        DialogUtil.closeDialog(mDialog);
                    }
                }).start();
            }
        });

        but_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("关闭");
                mDialog = DialogUtil.createLoadingDialog(MainActivity.this, "正在更改设置...");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String reply = LoginOfPost(sendurl, "&val=35");
                        System.out.println("服务器返回:" + reply);
                        if (reply == null) {
                            showToast("设置失败,请检查网络!!");
                        } else {
                            showToast("设置成功!!");
                        }
                        DialogUtil.closeDialog(mDialog);
                    }
                }).start();
            }
        });

    }

    /**
     * 使用POST访问网络
     *
     * @return 服务器返回的结果
     */

    public static String LoginOfPost(String turl, String str) {

        HttpURLConnection connection = null;
        try {
            URL url = new URL(turl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(10000);
/**
 *
 * public void setDoOutput(boolean dooutput)
 * 将此 URLConnection 的 doOutput 字段的值设置为指定的值.
 * URL 连接可用于输入和/或输出。如果打算使用 URL 连接进行输出,
 * 则将 DoOutput 标志设置为 true;如果不打算使用,则设置为 false。默认值为 false。
 * 简单一句话:get请求的话默认就行了,post请求需要setDoOutput(true),这个默认是false的。
 */
            connection.setDoOutput(true);
            String data = str;
            OutputStreamWriter outputStream = null;
            outputStream = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            outputStream.write(data);
            outputStream.flush();
            outputStream.close();
            connection.connect();
            if (200 == connection.getResponseCode()) {
                InputStream is = connection.getInputStream();
                String state = getStringFromInputStream(is);
                return state;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String getStringFromInputStream(InputStream is) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buff = new byte[1024];
        int len = -1;
        while ((len = is.read(buff)) != -1) {
            baos.write(buff, 0, len);
        }
        is.close();
        String html = baos.toString();
        baos.close();
        return html;
    }

    public void showToast(String msg) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG)
                        .show();
            }
        });
    }
}

其余代码就不上加了,想要源码可私聊。

改进版本可以参考链接:http://t.csdn.cn/HdiTj

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

点灯失败

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值