Android发送post请求方式 HttpURLConnection发与 okhttp发送 拼搏现实的明天。 2023-06-23 11:51 0阅读 0赞 ### 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' ![引包][watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQwODExMTcx_size_16_color_FFFFFF_t_70] [watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQwODExMTcx_size_16_color_FFFFFF_t_70]: https://img-blog.csdnimg.cn/20191218174951432.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQwODExMTcx,size_16,color_FFFFFF,t_70
还没有评论,来说两句吧...