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;
public class BaseRequest{
private static final int REQUEST_TIMEOUT = 60 * 1000;
public static final int HAND_REQUEST_SUCCESS = 300;
public static final int HAND_REQUEST_FAILURE = 400;
public static void postJsonData(final String reqUrl, final String jsonParam, 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()));
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "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();
System.out.println(res);
} else {
}
} catch (IOException e) {
}
}
}.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) {
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;
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 {
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);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
System.out.println(123);
}
如圖 : 引入
implementation 'com.squareup.okhttp3:okhttp:3.4.1'