List of usage examples for javax.net.ssl HttpsURLConnection setRequestMethod
public void setRequestMethod(String method) throws ProtocolException
From source file:com.starr.smartbuilds.service.DataService.java
public void getChampionsDataFromRiotAPI() throws IOException, ParseException { String line;/*from ww w.j a va 2s. com*/ String result = ""; URL url = new URL( "https://global.api.pvp.net/api/lol/static-data/euw/v1.2/champion?api_key=" + Constants.API_KEY); //Get connection HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("GET"); int responseCode = conn.getResponseCode(); System.out.println("resp:" + responseCode); System.out.println("resp msg:" + conn.getResponseMessage()); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); System.out.println("BUFFER----"); while ((line = br.readLine()) != null) { result += line; } conn.disconnect(); getChampionsFromData(result); }
From source file:com.starr.smartbuilds.service.DataService.java
private String getSummonerIdDataFromRiotAPI(String region, String summonerName) throws MalformedURLException, IOException, ParseException { String line;//from w w w . j av a2 s .co m String result = ""; URL url = new URL("https://" + region + ".api.pvp.net/api/lol/" + region + "/v1.4/summoner/by-name/" + summonerName + "?api_key=" + Constants.API_KEY); //Get connection HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("GET"); int responseCode = conn.getResponseCode(); System.out.println("resp:" + responseCode); System.out.println("resp msg:" + conn.getResponseMessage()); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); System.out.println("BUFFER----"); while ((line = br.readLine()) != null) { result += line; } conn.disconnect(); return result; }
From source file:com.starr.smartbuilds.service.DataService.java
private String getSummonerDataFromRiotAPI(String region, Long summonerID) throws MalformedURLException, IOException { String line;//from w w w .j a v a 2s .c o m String result = ""; URL url = new URL("https://" + region + ".api.pvp.net/api/lol/" + region + "/v2.5/league/by-summoner/" + summonerID + "/entry?api_key=" + Constants.API_KEY); //Get connection HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("GET"); int responseCode = conn.getResponseCode(); System.out.println("resp:" + responseCode); System.out.println("resp msg:" + conn.getResponseMessage()); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); System.out.println("BUFFER----"); while ((line = br.readLine()) != null) { result += line; } conn.disconnect(); return result; }
From source file:org.wso2.carbon.sample.service.EventsManagerService.java
public String performPostCall(String requestURL, Map<String, String> postDataParams) throws HttpException, IOException { URL url;//from w w w .java 2s. c o m String response = ""; url = new URL(requestURL); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setReadTimeout(15000); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(getPostDataString(postDataParams)); writer.flush(); writer.close(); os.close(); int responseCode = conn.getResponseCode(); if (responseCode == HttpsURLConnection.HTTP_OK) { String line; BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = br.readLine()) != null) { response += line; } } else { response = ""; throw new HttpException(responseCode + ""); } return response; }
From source file:com.esri.geoevent.test.performance.bds.BdsEventConsumer.java
private int getMsLayerCount(String url) { int cnt = -1; try {//w w w.ja va2 s . c om URL obj = new URL(url + "/query"); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); //add request header con.setRequestMethod("POST"); con.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); con.setRequestProperty("Accept", "text/plain"); String urlParameters = "where=" + URLEncoder.encode("1=1", "UTF-8") + "&returnCountOnly=" + URLEncoder.encode("true", "UTF-8") + "&f=" + URLEncoder.encode("json", "UTF-8"); // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //print result String jsonString = response.toString(); JSONTokener tokener = new JSONTokener(jsonString); JSONObject root = new JSONObject(tokener); cnt = root.getInt("count"); } catch (Exception e) { cnt = -2; } finally { return cnt; } }
From source file:org.talend.components.marketo.runtime.client.MarketoBulkExecClient.java
public BulkImportResult executePostFileRequest(Class<?> resultClass, String filePath) throws MarketoException { String boundary = "Talend_tMarketoBulkExec_" + String.valueOf(System.currentTimeMillis()); try {//from w ww .j av a 2 s . c o m URL url = new URL(current_uri.toString()); HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection(); urlConn.setRequestMethod("POST"); urlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); urlConn.setRequestProperty("accept", "text/json"); urlConn.setDoOutput(true); String requestBody = buildRequest(filePath); // build the request body PrintWriter wr = new PrintWriter(new OutputStreamWriter(urlConn.getOutputStream())); wr.append("--" + boundary + "\r\n"); wr.append("Content-Disposition: form-data; name=\"file\";filename=\"" + filePath + "\";\r\n"); wr.append("Content-type: text/plain; charset=\"utf-8\"\r\n"); wr.append("Content-Transfer-Encoding: text/plain\r\n"); wr.append("MIME-Version: 1.0\r\n"); wr.append("\r\n"); wr.append(requestBody); wr.append("\r\n"); wr.append("--" + boundary); wr.flush(); wr.close(); int responseCode = urlConn.getResponseCode(); if (responseCode == 200) { InputStream inStream = urlConn.getInputStream(); InputStreamReader reader = new InputStreamReader(inStream); Gson gson = new Gson(); return (BulkImportResult) gson.fromJson(reader, resultClass); } else { LOG.error("POST request failed: {}", responseCode); throw new MarketoException(REST, responseCode, "Request failed! Please check your request setting!"); } } catch (IOException e) { LOG.error("POST request failed: {}", e.getMessage()); throw new MarketoException(REST, e.getMessage()); } }
From source file:org.wso2.carbon.appmgt.sampledeployer.http.HttpHandler.java
public String doPostHttps(String backEnd, String payload, String your_session_id, String contentType) throws IOException { URL obj = new URL(backEnd); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); if (!your_session_id.equals("")) { con.setRequestProperty("Cookie", "JSESSIONID=" + your_session_id); }//from www . j a va 2 s .c om if (!contentType.equals("")) { con.setRequestProperty("Content-Type", contentType); } con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(payload); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); if (responseCode == 200) { BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); if (your_session_id.equals("")) { String session_id = response.substring((response.lastIndexOf(":") + 3), (response.lastIndexOf("}") - 2)); return session_id; } else if (your_session_id.equals("header")) { return con.getHeaderField("Set-Cookie"); } return response.toString(); } return null; }
From source file:com.persistent.cloudninja.scheduler.DeploymentMonitor.java
/** * Gets the information regarding the roles and their instances * of the deployment. It makes a call to REST API and gets the XML response. * //from w w w . ja va2s . c om * @return XML response * @throws IOException */ public StringBuffer getRoleInfoForDeployment() throws IOException { StringBuffer response = new StringBuffer(); System.setProperty("javax.net.ssl.keyStoreType", "pkcs12"); StringBuffer keyStore = new StringBuffer(); keyStore.append(System.getProperty("java.home")); LOGGER.debug("java.home : " + keyStore.toString()); if (keyStore.length() == 0) { keyStore.append(System.getenv("JRE_HOME")); LOGGER.debug("JRE_HOME : " + keyStore.toString()); } keyStore.append(File.separator + "lib\\security\\CloudNinja.pfx"); System.setProperty("javax.net.ssl.keyStore", keyStore.toString()); System.setProperty("javax.net.debug", "ssl"); System.setProperty("javax.net.ssl.keyStorePassword", keyStorePassword); System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword); SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); // form the URL which will return the response // containing info of roles and their instances. StringBuffer strURL = new StringBuffer(host); strURL.append(subscriptionId); strURL.append("/services/hostedservices/"); strURL.append(hostedServiceName); strURL.append("/deploymentslots/"); strURL.append(deploymentType); URL url = new URL(strURL.toString()); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setSSLSocketFactory(sslSocketFactory); connection.setRequestMethod("GET"); connection.setAllowUserInteraction(false); // set the x-ms-version in header which is a compulsory parameter to get response connection.setRequestProperty("x-ms-version", "2011-10-01"); connection.setRequestProperty("Content-type", "text/xml"); connection.setRequestProperty("accept", "text/xml"); // get the response as input stream InputStream inputStream = connection.getInputStream(); InputStreamReader streamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(streamReader); String string = null; while ((string = bufferedReader.readLine()) != null) { response.append(string); } return response; }
From source file:cn.bidaround.ytcore.kaixin.KaixinUtil.java
/** * ??http// w w w . j a v a2 s .com * * @param context * * @param requestURL * ?? * @param httpMethod * GET POST * @param params * key-value??key???value???Stringbyte[] * @param photos * key-value??? keyfilename * value????InputStreambyte[] * ?InputStreamopenUrl? * @return ?JSON * @throws IOException */ public static String openUrl(Context context, String requestURL, String httpMethod, Bundle params, Map<String, Object> photos) throws IOException { OutputStream os; if (httpMethod.equals("GET")) { requestURL = requestURL + "?" + encodeUrl(params); } URL url = new URL(requestURL); HttpsURLConnection conn = (HttpsURLConnection) getConnection(context, url); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " KaixinAndroidSDK"); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestProperty("Connection", "close"); conn.setRequestProperty("Charsert", "UTF-8"); if (!httpMethod.equals("GET")) { Bundle dataparams = new Bundle(); // for (String key : params.keySet()) { // if (params.getByteArray(key) != null) { // dataparams.putByteArray(key, params.getByteArray(key)); // } // } String BOUNDARY = KaixinUtil.md5(String.valueOf(System.currentTimeMillis())); // ? String endLine = "\r\n"; conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); os.write(("--" + BOUNDARY + endLine).getBytes()); os.write((encodePostBody(params, BOUNDARY)).getBytes()); os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); if (!dataparams.isEmpty()) { for (String key : dataparams.keySet()) { os.write(("Content-Disposition: form-data; name=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes()); os.write(dataparams.getByteArray(key)); os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); } } if (photos != null && !photos.isEmpty()) { for (String key : photos.keySet()) { Object obj = photos.get(key); if (obj instanceof InputStream) { InputStream is = (InputStream) obj; try { os.write(("Content-Disposition: form-data; name=\"pic\";filename=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type:application/octet-stream\r\n\r\n").getBytes()); byte[] data = new byte[UPLOAD_BUFFER_SIZE]; int nReadLength = 0; while ((nReadLength = is.read(data)) != -1) { os.write(data, 0, nReadLength); } os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); } finally { try { if (null != is) { is.close(); } } catch (Exception e) { Log.e(LOG_TAG, "Exception on closing input stream", e); } } } else if (obj instanceof byte[]) { byte[] byteArray = (byte[]) obj; os.write(("Content-Disposition: form-data; name=\"pic\";filename=\"" + key + "\"" + endLine) .getBytes()); os.write(("Content-Type:application/octet-stream\r\n\r\n").getBytes()); os.write(byteArray); os.write((endLine + "--" + BOUNDARY + endLine).getBytes()); } else { Log.e(LOG_TAG, "?"); } } } os.flush(); } String response = ""; try { response = read(conn.getInputStream()); } catch (FileNotFoundException e) { response = read(conn.getErrorStream()); } return response; }
From source file:com.esri.geoevent.test.tools.GetMapServiceCountRunnable.java
private int getMsLayerCount(String url) { int cnt = -1; try {// w w w . j a va2 s . c o m URL obj = new URL(url + "/query"); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod("POST"); con.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); con.setRequestProperty("Accept", "text/plain"); String urlParameters = "where=" + URLEncoder.encode("1=1", "UTF-8") + "&returnCountOnly=" + URLEncoder.encode("true", "UTF-8") + "&f=" + URLEncoder.encode("json", "UTF-8"); // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //print result String jsonString = response.toString(); JSONTokener tokener = new JSONTokener(jsonString); JSONObject root = new JSONObject(tokener); cnt = root.getInt("count"); } catch (Exception e) { cnt = -2; } finally { return cnt; } }