1.https post 连接请求
PrintWriter out = null;
BufferedReader in = null;
String param = "grant_type="+grant_type+"&client_id="+client_id+"&client_secret="+client_secret+"&scope="+scope+"";
try {
URL realUrl = new URL(tokenUrl);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
// return result;
/* <dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.57</version>
</dependency>*/
JSONObject jsonObject = JSONObject.parseObject(result);
Token token = JSONObject.toJavaObject(jsonObject, Token.class);
return token;
2.http util
public static HttpURLConnection getHttpURLOpenConnection(URL url, String accessToken, Boolean fromAccessToken) throws Exception {
HttpURLConnection httpUrlConnection;
try {
log.info("getHttpURLOpenConnection 1");
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers()
{ return null; }
public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType)
{ }
public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType)
{ }
}
};
log.info("getHttpURLOpenConnection 2");
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
throw new Exception("SSL Exception at " + getCurrentTime());
}
log.info("getHttpURLOpenConnection 3");
httpUrlConnection = (HttpURLConnection) url.openConnection();
log.info("getHttpURLOpenConnection 4");
httpUrlConnection.setRequestProperty("Authorization", accessToken==null? "Basic " : accessToken);
if(fromAccessToken) {
httpUrlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpUrlConnection.setRequestProperty("Accept", "application/x-www-form-urlencoded");
}else {
httpUrlConnection.setRequestProperty("Content-Type", "application/json");
httpUrlConnection.setRequestProperty("Accept", "application/json");
}
httpUrlConnection.setDoOutput(true);
log.info("getHttpURLOpenConnection 5");
//String lookup_string = "GRAPHAPI_CONN_TIMEOUT";
GRAPHAPI_CONN_TIMEOUT = "30000";
log.info("GRAPHAPI_CONN_TIMEOUT : " + GRAPHAPI_CONN_TIMEOUT);
//lookup_string = "GRAPHAPI_READ_TIMEOUT";
GRAPHAPI_READ_TIMEOUT = "180000";
log.info("GRAPHAPI_READ_TIMEOUT : " + GRAPHAPI_READ_TIMEOUT);
if(GRAPHAPI_CONN_TIMEOUT==null || GRAPHAPI_CONN_TIMEOUT.trim().isEmpty()) {
httpUrlConnection.setConnectTimeout(10000); // 10 seconds
}else {
try {
httpUrlConnection.setConnectTimeout(Integer.valueOf(GRAPHAPI_CONN_TIMEOUT));
} catch (Exception e)
{
log.info("GRAPHAPI_CONN_TIMEOUT set as default value due to error on config file! ");
httpUrlConnection.setConnectTimeout(10000); // 10 seconds
}
}
if(GRAPHAPI_READ_TIMEOUT==null || GRAPHAPI_READ_TIMEOUT.trim().isEmpty()) {
httpUrlConnection.setReadTimeout(180000); // 180 seconds
}else {
try {
httpUrlConnection.setReadTimeout(Integer.valueOf(GRAPHAPI_READ_TIMEOUT));
} catch (Exception e)
{
log.info("GRAPHAPI_READ_TIMEOUT set as default value due to error on config file! ");
httpUrlConnection.setReadTimeout(180000); // 180 seconds
}
}
return httpUrlConnection;
} catch (Exception e) {
throw new Exception("Fail to Open Http connection :: ", e);
}
}
public static String getHttpResponseToString(InputStream inputstream) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader((inputstream)));
String output;
String response = "";
try {
while ((output = br.readLine()) != null) {
response = response + output;
}
br.close();
return response;
} catch (Exception e) {
throw new Exception("Fail to get HttpResponse to String :: ", e);
}
}
public static String mapObjectToString(Object object) throws Exception {
ObjectMapper om = new ObjectMapper();
try {
return om.writeValueAsString(object);
} catch (JsonProcessingException e) {
throw new Exception("Fail to Parse Json :: ", e);
}
}
public static <T> T mapStringToObject(String json, Class<T> c) throws Exception {
//import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper om = new ObjectMapper();
try {
return om.readValue(json, c);
} catch (IOException e) {
throw new Exception("Fail to Parse Json :: " + c.getName(), e);
}
}
public static String getParamsString(Map<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
result.append("&");
}
String resultString = result.toString();
return resultString.length() > 0 ? resultString.substring(0, resultString.length() - 1) : resultString;
}
public static String getCurrentTime() {
try {
SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
return df.format(new Date());
} catch (Exception e) {
return (new Date()).toString();
}
}
//PDF文件转byte数组
InputStream in = new FileInputStream(GraphAPIConstant.UPLOAD_FILE_PATH+fileName);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] data = new byte[1024 * 4];
int n = 0;
while ((n = in.read(data)) != -1) {
out.write(data, 0, n);
}
in.close();
httpUrlConnection.setRequestProperty("Content-Length", String.valueOf(data.length));
OutputStream outputStream = httpUrlConnection.getOutputStream();
outputStream.write(data);
outputStream.flush();
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import com.ericsson.dcpbss.si.common.exception.KongErrorEnum;
import com.ericsson.dcpbss.si.common.exception.KongException;
import com.ericsson.dcpbss.si.utils.RestUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
private static final String CONTENT_TYPE_VALUE = "application/json;charset=UTF-8";
@Autowired
private RestTemplate restTemplate;
private ObjectMapper mapper = new ObjectMapper();
public Map<String, Object> getMapByString(String str) throws IOException {
return mapper.readValue(str, new TypeReference<Map<String, Object>>() {
});
}
public Map<String, Object> getJwtKeyAndSecret(String url) {
String uri = "";
try {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set("Content-Type", CONTENT_TYPE_VALUE);
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(url);
uri = uriComponentsBuilder.toUriString();
HttpEntity<?> entity = new HttpEntity<>(null);
HttpEntity<Map<String, Object>> response = restTemplate.exchange(uri, HttpMethod.POST, entity,
RestUtils.defaultMapTypeRef);
Map<String, Object> responseMap = response.getBody();
LOGGER.info(" successfully", responseMap);
return responseMap;
public static final ParameterizedTypeReference<Map<String, Object>> defaultMapTypeRef = new ParameterizedTypeReference<Map<String, Object>>() {};