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”:""}

GitHub 加速计划 / js / json
41.72 K
6.61 K
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:1 个月前 )
960b763e 4 个月前
8c391e04 6 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐