get 请求获取接口信息
//get 请求获取接口信息
public static String getUrl(String url1,String strcity) throws Exception{
//拼地址
String apiUrl = String.format(url1,strcity);
//开始请求
URL url= new URL(apiUrl);
URLConnection open = url.openConnection();
InputStream input = open.getInputStream();
//这里转换为String,带上包名,怕你们引错包
String result = org.apache.commons.io.IOUtils.toString(input,"utf-8");
//输出
return result;
}
接口请求方式合并(可以传参)
/*
* requestUrl 请求地址
* requestMethod 请求方式
* outPutStr 提交数据
* */
public static JSONObject getRequestUrl(String requestUrl, String requestMethod, String outPutStr){
JSONObject jSONObject=null;
StringBuffer buffer=new StringBuffer();
try {
TrustManager[] tm={new MyX509TrustManager()};
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null,tm,new java.security.SecureRandom());
SSLSocketFactory ssf = sslContext.getSocketFactory();
//URL url=new URL(requestUrl);
URL url = new URL(null,requestUrl,new sun.net.www.protocol.https.Handler());
HttpsURLConnection httUrlConn=(HttpsURLConnection) url.openConnection();
httUrlConn.setSSLSocketFactory(ssf);
httUrlConn.setDoOutput(true);
httUrlConn.setDoInput(true);
httUrlConn.setUseCaches(false);
httUrlConn.setRequestMethod(requestMethod);
if("GET".equalsIgnoreCase(requestMethod)){
httUrlConn.connect();
}
//当有数据需要提交时
if(null!= outPutStr){
OutputStream outputStream = httUrlConn.getOutputStream();
outputStream.write(outPutStr.getBytes("UTF-8"));
outputStream.close();
}
//将返回的输入流转成换成字符串
InputStream inputStream = httUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str=null;
while ((str =bufferedReader.readLine())!= null){
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
//释放资源
inputStream.close();
inputStream =null;
httUrlConn.disconnect();
jSONObject = JSONObject.fromObject(buffer.toString());
} catch (ConnectException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return jSONObject;
}