Android 利用原生java发送POST请求json参数(可提交大量数据)

1.请求工具类

package zjhj.com.myapplication.http.base;

import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import zjhj.com.dev.utils.L;

/**
 * CreateTime 2019/9/24 09:28
 * Author LiuShiHua
 * Description:
 */
public class BaseRequest {
    private static final int REQUEST_TIMEOUT = 60 * 1000;//设置超时60秒
    public static final int HAND_REQUEST_SUCCESS = 300;
    public static final int HAND_REQUEST_FAILURE = 400;

    /**
     * post请求
     *
     * @param reqUrl
     * @param jsonParam json对象的String参数
     * @param handler   返回数据接收handler
     * @param type      返回请求类型
     */
    public static void postJsonData(final String reqUrl, final String jsonParam, @NonNull final Handler handler, final int type) {
        if (reqUrl == null) return;
        L.d("postJsonData请求地址:" + reqUrl);
        L.d("postJsonData请求参数:" + jsonParam);
        new Thread() {
            @Override
            public void run() {
                super.run();
                BufferedReader reader = null;
                try {
                    URL url = new URL(reqUrl);// 创建连接
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setDoOutput(true);
                    connection.setConnectTimeout(REQUEST_TIMEOUT);
                    connection.setDoInput(true);
                    connection.setUseCaches(false);
                    connection.setInstanceFollowRedirects(true);
                    connection.setRequestMethod("POST"); // 设置请求方式
                    connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
                    //设置发送数据长度(用于发送大量数据使用)
                    connection.setRequestProperty("Content-Length", String.valueOf(jsonParam.length()));
                    //一定要用BufferedReader 来接收响应, 使用字节来接收响应的方法是接收不到内容的
                    OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
                    out.append(jsonParam);
                    out.flush();
                    out.close();
                    L.d(String.valueOf(connection.getResponseCode()));
                    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        // 读取响应
                        reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                        String line;
                        String res = "";
                        while ((line = reader.readLine()) != null) {
                            res += line;
                        }
                        L.d(res);
                        reader.close();
                        //通过handler来回传返回数据
                        Message msg = new Message();
                        msg.obj = res;
                        msg.arg1 = HAND_REQUEST_SUCCESS;
                        msg.what = type;
                        handler.sendMessage(msg);
                    } else {
                        Message msg = new Message();
                        msg.obj = "请求错误," + connection.getResponseCode();
                        msg.arg1 = HAND_REQUEST_FAILURE;
                        msg.what = type;
                        handler.sendMessage(msg);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    Message msg = new Message();
                    msg.obj = "请求异常,请检查网络";
                    msg.arg1 = HAND_REQUEST_FAILURE;
                    msg.what = type;
                    handler.sendMessage(msg);
                    L.e("POST IOException", e);
                }
            }
        }.start();
    }


    public static void getData(final String getUrl, final Handler handler, final int type) {
        L.d("getData请求地址:" + getUrl);
        new Thread() {
            @Override
            public void run() {
                super.run();
                String acceptData = "";
                try {
                    URL url = new URL(getUrl);// 创建连接
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(REQUEST_TIMEOUT);
                    connection.setRequestMethod("GET"); // 设置请求方式
                    connection.connect();
                    L.d(String.valueOf(connection.getResponseCode()));
                    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
//                        Log.i("接受到的数据:", String.valueOf(connection.getResponseCode()));
                        InputStream inputStream = connection.getInputStream();
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
                        String line;
                        while ((line = bufferedReader.readLine()) != null) { //不为空进行操作
                            acceptData += line;
                        }
                        L.d(acceptData);
                        if (handler != null) {
                            Message msg = new Message();
                            msg.obj = acceptData;
                            msg.arg1 = HAND_REQUEST_SUCCESS;
                            msg.what = type;
                            handler.sendMessage(msg);
                        }
                    } else {
                        Message msg = new Message();
                        msg.obj = "请求错误," + connection.getResponseCode();
                        msg.arg1 = HAND_REQUEST_FAILURE;
                        msg.what = type;
                        handler.sendMessage(msg);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    Message msg = new Message();
                    msg.obj = "请求异常,请检查网络";
                    msg.arg1 = HAND_REQUEST_FAILURE;
                    msg.what = type;
                    handler.sendMessage(msg);
                    L.e("GET IOException", e);
                }
            }
        }.start();
    }
}

2.调用(传入handler来接收返回值 我这里没传)

		Map<String, Object> params = new HashMap<>();
        params.put("deviceAlarmType", 35);
        params.put("sn", "SN-IFMJVGSCOF4LSK7T-del");
        OldRequetsUtils.postJsonData(new Gson().toJson(params), handler,1);

日志效果:
OldRequetsUtils: {“code”:0,“message”:“操作成功”,“obj”:{},“tokenStr”:""}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值