Java实现get与post的请求提交
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.util.Map.Entry;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import net.sf.json.JSONObject;
//编码
private static String encoding = "UTF-8";
//加密方式
private static String algorithm = "HmacSHA256";
//项目ID
private static String projectId = "1001";
//项目密钥
private static String projectSecret = "945e152673f462";
/**
* main方法调用
* @param args
*/
public static void main(String[] args) {
try {
doRequest();
} catch (Exception e) {
e.printStackTrace();
}
}
/***
* 请求
* @throws Exception
*/
public static void doRequest()throws Exception {
String signature = null;
String resultJSON = null;
String urlPath = null;
//设置请求参数
String apply = setJSONStr();
//计算签名值
signature = getHMACHexString(apply, projectSecret, algorithm, encoding);
////////////////////get请求//////////////////////////
//请求地址
urlPath = "http://localhost:8013/api/roles?page=0&size=10&sort=id%2Cdesc";
//模拟请求
resultJSON = sendGet(urlPath);
////////////////////post请求//////////////////////////
urlPath = "http://localhost:8013/V1/organizeSeals/create";
//模拟请求
resultJSON = sendPost(urlPath,signature,apply);
//解析
JSONObject result = JSONObject.fromObject(resultJSON);
System.out.println("返回值为:"+result);
//获取返回结果中的错误信息,errCode错误码与msg错误信息
String errCode = result.getString("errCode");
String msg = result.getString("msg");
}
/***
* 模拟发送POST请求
*
* @param jsonStr
* @return
* @throws Exception
*/
public static String sendPost(String urlPath, String signature, String jsonStr) throws Exception {
String result = null;
// 建立连接
URL url = new URL(urlPath);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
// 设置Headers参数
httpConn.setDoOutput(true); //需要输出
httpConn.setDoInput(true); //需要输入
httpConn.setUseCaches(false); //不允许缓存
httpConn.setRequestMethod("POST"); //设置POST方式连接
// 设置Headers属性
for (Entry<String, String> entry : getHeaders(signature, jsonStr).entrySet()) {
httpConn.setRequestProperty(entry.getKey(), entry.getValue());
}
// 连接会话
httpConn.connect();
// 建立输入流,向指向的URL传入参数
DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
// 设置请求参数
dos.write(jsonStr.toString().getBytes("UTF-8"));
System.out.println(jsonStr);
dos.flush();
dos.close();
// 获得响应状态
int resultCode = httpConn.getResponseCode();
if (HttpURLConnection.HTTP_OK == resultCode) {
StringBuffer sb = new StringBuffer();
String readLine = new String();
BufferedReader responseReader = new BufferedReader(
new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
while ((readLine = responseReader.readLine()) != null) {
sb.append(readLine);
}
// System.out.println(httpConn.get.getRequestURI());
responseReader.close();
result = sb.toString();
}
return result;
}
/**
* 向指定URL发送GET方法的请求
*
* @param url 发送请求的URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url) {
String result = "";
BufferedReader in = null;
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置Headers属性
connection.setRequestProperty("X-timevale-project-id", "1000000");
connection.setRequestProperty("X-timevale-signature","c05bc7a9b1a3e057ec79f424a7a809e3598e59191e59e0");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true); //需要输出
connection.setDoInput(true); //需要输入
connection.setUseCaches(false); //不允许缓存
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
// for (String key : map.keySet()) {
// System.out.println(key + "--->" + map.get(key));
// }
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/***
* 设置请求参数
*
* @return
*/
public static String setJSONStr() {
JSONObject All_JSON = new JSONObject();
All_JSON.put("organizeId", "28a46585-8ac2f6-1a0266");
StandardApiAddSealUserParam ds=new StandardApiAddSealUserParam();
ds.setAccountId("73e6203d-9878ec-99f1cb8a2fb5");
List ls=new ArrayList();
ls.add(ds);
All_JSON.put("sealHandler",ls);
return All_JSON.toString();
}
/***
* 设置Headers报头信息(post请求终使用)
*
* @param jsonStr
* @return
* @throws Exception
*/
public static Map<String, String> getHeaders(String signature, String jsonStr) throws Exception {
Map<String, String> headersMap = new LinkedHashMap<String, String>();
headersMap.put("X-timevale-project-id", projectId);
headersMap.put("X-timevale-signature", signature); // 请求参数和projectSecret参数通过HmacSHA256加密的16进制字符串
headersMap.put("signature-algorithm", algorithm);
headersMap.put("Content-Type", "application/json");
return headersMap;
}
/***
* 获取HMAC加密后的16进制字符串(Hash Message Authentication Code,散列消息鉴别码)
*
* @param data 加密前数据
* @param key 密钥
* @param algorithm HmacMD5 HmacSHA1 HmacSHA256 HmacSHA384 HmacSHA512
* @param encoding 编码格式
* @return HMAC加密后16进制字符串
* @throws Exception
*/
public static String getHMACHexString(String data, String key, String algorithm, String encoding) throws Exception {
return byte2hex(encryptHMACByAlgorithm(data, key, algorithm, encoding));
}
/***
* 将byte[]转成16进制字符串
*
* @param data HMAC加密后数据
* @return 16进制字符串
*/
public static String byte2hex(byte[] data) {
StringBuilder hash = new StringBuilder();
String stmp;
for (int n = 0; data != null && n < data.length; n++) {
stmp = Integer.toHexString(data[n] & 0XFF);
if (stmp.length() == 1){
hash.append('0');
}
hash.append(stmp);
}
return hash.toString();
}
/***
* HMAC加密(Hash Message Authentication Code,散列消息鉴别码)
*
* @param data 加密前数据
* @param key 密钥
* @param algorithm HmacMD5 HmacSHA1 HmacSHA256 HmacSHA384 HmacSHA512
* @param encoding 编码格式
* @return HMAC加密后数据
* @throws Exception
*/
public static byte[] encryptHMACByAlgorithm(String data, String key, String algorithm, String encoding) throws Exception {
Mac mac = Mac.getInstance(algorithm);
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(encoding), algorithm);
mac.init(secretKey);
mac.update(data.getBytes(encoding));
return mac.doFinal();
}