一、Http请求
public static String httpRequestSend(String partUrl, JSONObject params) throws Exception{
String zyUrl = getZyUrl(partUrl);
params.put("accessToken", accessToken);
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String timeStamp = sdf.format(date);//请求接口时,请求方当前时间毫
params.put("timeStamp", timeStamp);
HashMap<String,String> map = new HashMap<String,String>();
map.put("Content-Type", "application/json");
String dataResult= HttpRequestProxy.send(zyUrl, params.toString(), map, "utf-8");
return dataResult;
}
一、HttpRequestProxy.send()
/**
* @param requestUrl
* @param content
* @param requestProperties
* @param charset "utf-8"
* @return
* @throws Exception
*/
public static String send(String requestUrl, String content, HashMap<String, String> requestProperties,
String charset) throws Exception {
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
if (requestProperties != null) {
for (String key : requestProperties.keySet()) {
String keyValue = requestProperties.get(key);
connection.setRequestProperty(key, keyValue);
if ("ConnectTimeOut".equalsIgnoreCase(key)) {
connection.setConnectTimeout(Integer.parseInt(keyValue));
} else if ("ReadTimeOut".equalsIgnoreCase(key)) {
connection.setReadTimeout(Integer.parseInt(keyValue));
}
}
}
OutputStream outStream = connection.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(outStream, java.nio.charset.Charset.forName(charset));
String response = null;
try {
try {
osw.write(content);
} finally {
osw.close();
outStream.close();
}
InputStream inStream = null;
InputStreamReader inStreamReader = null;
try {
inStream = connection.getInputStream();
} catch (Exception exception) {
inStream = connection.getErrorStream();
if (inStream == null) {
throw exception;
}
}
try {
inStreamReader = new InputStreamReader(inStream, java.nio.charset.Charset.forName(charset));
} catch (Exception readEx) {
inStream.close();
throw readEx;
}
StringWriter sw = new StringWriter();
char[] buf = new char[8096];
int size = 0;
try {
while ((size = inStreamReader.read(buf)) != -1)
sw.write(buf, 0, size);
response = sw.toString();
} finally {
sw.close();
inStreamReader.close();
inStream.close();
}
} finally {
connection.disconnect();
}
return response;
}