Android發送post請求方式 HttpURLConnection發與 okhttp發送

HttpURLConnection 發送

package com.example.MyLibrary;

import android.os.Handler;
import android.os.Message;

import androidx.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;

/**
 * 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, /*final Handler handler,*/ final int type) {
        if (reqUrl == null) return ;
        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();

                    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;
                        }

                        reader.close();
                      /*  //通過handler來回傳返回數據
                        Message msg = new Message();
                        msg.obj = res;
                        msg.arg1 = HAND_REQUEST_SUCCESS;
                        msg.what = type;
                        handler.sendMessage(msg);*/
                        System.out.println(res);



                    } 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);*/
                }
            }
        }.start();

    }


    public static void getData(final String getUrl, final Handler handler, final int type) {

        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();

                    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;
                        }

                        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);

                }
            }
        }.start();
    }
}

    //發送請求
	Map<String, Object> params = new HashMap<>();
     params.put("deviceAlarmType", 35);
     params.put("sn", "SN-IFMJVGSCOF4LSK7T-del");
     BaseRequest.postJsonData(url ,"",1);

okhttp3 發送請求

    private static final int REQUEST_TIMEOUT = 60 * 60;//設置超時60秒
    public static final int HAND_REQUEST_SUCCESS = 300;
    public static final int HAND_REQUEST_FAILURE = 400;
    public final static int CONNECT_TIMEOUT = 60;
    public final static int READ_TIMEOUT = 100;
    public final static int WRITE_TIMEOUT = 60;
    public static final OkHttpClient client = new OkHttpClient.Builder().retryOnConnectionFailure(true)
            .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)//設置讀取超時時間
            .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)//設置寫的超時時間
            .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)//設置連接超時時間
            .build();
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");



    public  void jsmethod_post(final UZModuleContext uzModuleContext) throws IOException {
      final   String url= uzModuleContext.optString("url");
        System.out.println(url);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        // 請求完整url:http://api.k780.com:88/?app=weather.future&weaid=1&&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json
                       // String url = "http://api.k780.com:88/";
                        OkHttpClient okHttpClient = new OkHttpClient();
                        String json = "{'app':'weather.future','weaid':'1','appkey':'10003'," +
                                "'sign':'b59bc3ef6191eb9f747dd4e83c99f2a4','format':'json'}";
                        RequestBody formBody = new FormBody.Builder().add("app", "weather.future")
                                .add("weaid", "1").add("appkey", "10003").add("sign",
                                        "b59bc3ef6191eb9f747dd4e83c99f2a4").add("format", "json")
                                .build();
                        Request request = new Request.Builder().url(url).post(formBody).build();
                        okhttp3.Response response = okHttpClient.newCall(request).execute();

                        String datas=response.body().string();
                        System.out.println(datas);
                        JSONObject ret = new JSONObject();
                        ret.put("data",datas);
                        uzModuleContext.success(ret);
                       // Toast.makeText(mContext,response.body().string(),Toast.LENGTH_SHORT).show();
                        //Log.i(TAG, response.body().string());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        System.out.println(123);
        }

如圖 : 引入

implementation 'com.squareup.okhttp3:okhttp:3.4.1'

引包

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章