HttpsURLConnection报文头报文体使用
POST请求
private static String TAG = "HttpConnection";
private static String POST_URL = "https://www.baidu.com";
private static String GET_URL = "http://www.baidu.com";
private static String data = "{\"name\":\"Marry\",\"age\":\"17\"}";
private static String getData = "name=Marry&age=17";
public static void connectionPost(String appId, String timeS) {
Log.i(TAG, "[-] connectionPost");
try {
URL url = new URL(POST_URL);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setReadTimeout(30000);
conn.setConnectTimeout(10000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.setRequestProperty("appId ", appId);
conn.setRequestProperty("timestamps ", timeS);
Log.i(TAG, "请求报文体:" + data.toString().replace("\\", ""));
OutputStream os = conn.getOutputStream();
os.write(data.toString().replace("\\", "").getBytes("UTF-8"));
os.flush();
int code = conn.getResponseCode();
if (code != 200) {
Log.e(TAG, "[-] verfReq: verify error=网络错误");
return;
}
InputStream is = conn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[8192];
int r = 0;
while ((r = is.read(buf)) != -1) {
baos.write(buf, 0, r);
}
String respStr = new String(baos.toByteArray(), "UTF-8");
Log.d(TAG, "[+] verfReq: respStr=" + respStr);
} catch (Exception e) {
e.printStackTrace();
}
}
GET请求
public static boolean connectGET(String appId, String bizId) {
String RESULT_URL = GET_URL + "?"+getData;
boolean isVerifySuc = false;
try {
URL url = new URL(RESULT_URL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(30000);
conn.setConnectTimeout(10000);
conn.setDoInput(true);
conn.setDoOutput(false);
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.setRequestProperty("appId ", appId);
conn.setRequestProperty("bizId ", bizId);
int code = conn.getResponseCode();
if (code != 200) {
Log.e(TAG, "[-] verfReq: verify error=网络错误");
return false;
}
InputStream is = conn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[8192];
int r = 0;
while ((r = is.read(buf)) != -1) {
baos.write(buf, 0, r);
}
String respStr = new String(baos.toByteArray(), "UTF-8");
Log.d(TAG, "[+] verfReq: respStr=" + respStr);
} catch (Exception e) {
Log.e(TAG, "[-] verfReq: verify error=", e);
}
return isVerifySuc;
}
子线程中调用
必须在子线程中调用
new Thread(new Runnable() {
@Override
public void run() {
HttpConnection.connectGET("111","222");
}
}).start();