List of usage examples for javax.net.ssl HttpsURLConnection getInputStream
public InputStream getInputStream() throws IOException
From source file:Main.IrcBot.java
public static void postGit(String pasteBinSnippet, PrintWriter out) { try {// w ww . jav a 2 s . c o m String url = "https://api.github.com/gists"; URL obj = new URL(url); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); //add reuqest header JSONObject x = new JSONObject(); JSONObject y = new JSONObject(); JSONObject z = new JSONObject(); z.put("content", pasteBinSnippet); y.put("index.txt", z); x.put("public", true); x.put("description", "LPBOT"); x.put("files", y); con.setRequestMethod("POST"); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String urlParameters = "public=true&description=LPBOT"; // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(x.toString()); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + urlParameters); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //print result JSONObject gitResponse = new JSONObject(response.toString()); String newGitUrl = gitResponse.getString("html_url"); if (newGitUrl.length() > 0) { out.println("PRIVMSG #learnprogramming :The paste on Git: " + newGitUrl); } System.out.println(newGitUrl); } catch (Exception p) { } }
From source file:com.longtime.ajy.support.weixin.HttpsKit.java
/** * ??Post//from w w w. ja v a 2 s .c o m * * @param url * @param params * @return * @throws IOException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws KeyManagementException */ public static String post(String url, String params) {//throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException { OutputStream out = null; InputStream in = null; HttpsURLConnection http = null; try { StringBuffer bufferRes = null; TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); // SSLContextSSLSocketFactory SSLSocketFactory ssf = sslContext.getSocketFactory(); URL urlGet = new URL(url); http = (HttpsURLConnection) urlGet.openConnection(); // http.setConnectTimeout(TIME_OUT_CONNECT); // ? --?? http.setReadTimeout(TIME_OUT_READ); http.setRequestMethod("POST"); http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); http.setSSLSocketFactory(ssf); http.setDoOutput(true); http.setDoInput(true); http.connect(); out = http.getOutputStream(); out.write(params.getBytes("UTF-8")); out.flush(); in = http.getInputStream(); BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET)); String valueString = null; bufferRes = new StringBuffer(); while ((valueString = read.readLine()) != null) { bufferRes.append(valueString); } return bufferRes.toString(); } catch (Exception e) { logger.error(String.format("HTTP POST url=[%s] param=[%s] due to fail.", url, params), e); } finally { if (null != out) { try { out.close(); } catch (IOException e) { logger.error(String.format("HTTP POST url=[%s] param=[%s] close outputstream due to fail.", url, params), e); } } if (null != in) { try { in.close(); } catch (IOException e) { logger.error(String.format("HTTP POST url=[%s] param=[%s] close inputstream due to fail.", url, params), e); } } if (http != null) { // http.disconnect(); } } return StringUtils.EMPTY; }
From source file:xyz.karpador.godfishbot.commands.TestLoveCommand.java
@Override public CommandResult getReply(String params, Message message, String myName) { if (params == null) return new CommandResult("Please submit two names."); String[] names = params.split(" "); if (names.length < 2) return new CommandResult("Please submit two names."); try {/* w w w . j av a 2 s.c om*/ URL url = new URL("https://love-calculator.p.mashape.com/getPercentage" + "?fname=" + names[0] + "&sname=" + names[1]); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setRequestProperty("X-Mashape-Key", BotConfig.getInstance().getMashapeToken()); con.setRequestProperty("Accept", "application/json"); if (con.getResponseCode() == HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); String result = br.readLine(); JSONObject resultJson = new JSONObject(result); String cmdResult = names[0] + " and " + names[1] + " fit " + resultJson.getString("percentage") + "%.\n" + resultJson.getString("result"); return new CommandResult(cmdResult); } } catch (IOException | JSONException e) { e.printStackTrace(); } return null; }
From source file:xyz.karpador.godfishbot.commands.QuoteCommand.java
@Override public CommandResult getReply(String params, Message message, String myName) { try {/*from www .ja v a 2 s .c om*/ String cat = Main.Random.nextInt(2) == 0 ? "famous" : "movies"; URL url = new URL("https://andruxnet-random-famous-quotes.p.mashape.com/?cat=" + cat + "&count=1"); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setRequestProperty("X-Mashape-Key", BotConfig.getInstance().getMashapeToken()); con.setRequestProperty("Accept", "application/json"); con.setReadTimeout(5000); if (con.getResponseCode() == HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); String result = br.readLine(); JSONObject resultJson = new JSONObject(result); String cmdResult = "" + resultJson.getString("quote") + " - " + resultJson.getString("author"); return new CommandResult(cmdResult); } } catch (IOException | JSONException e) { e.printStackTrace(); } return null; }
From source file:tk.egsf.ddns.login.java
private String print_content(HttpsURLConnection con) { String ret = ""; if (con != null) { try {/* w w w. j av a 2s . c o m*/ System.out.println("****** Content of the URL ********"); BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); String input; while ((input = br.readLine()) != null) { ret += input; } br.close(); } catch (IOException e) { e.printStackTrace(); } } System.out.println(ret); return ret; }
From source file:it.bz.tis.integreen.carsharingbzit.api.ApiClient.java
public <T> T callWebService(ServiceRequest request, Class<T> clazz) throws IOException { request.request.technicalUser.username = this.user; request.request.technicalUser.password = this.password; ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.FIELD, Visibility.NONE) .setVisibility(PropertyAccessor.IS_GETTER, Visibility.PUBLIC_ONLY) .setVisibility(PropertyAccessor.GETTER, Visibility.PUBLIC_ONLY) .setVisibility(PropertyAccessor.SETTER, Visibility.PUBLIC_ONLY); mapper.enable(SerializationFeature.INDENT_OUTPUT); StringWriter sw = new StringWriter(); mapper.writeValue(sw, request);//from w ww . j a va 2s . c o m String requestJson = sw.getBuffer().toString(); logger.debug("callWebService(): jsonRequest:" + requestJson); URL url = new URL(this.endpoint); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); OutputStream out = conn.getOutputStream(); out.write(requestJson.getBytes("UTF-8")); out.flush(); int responseCode = conn.getResponseCode(); InputStream input = conn.getInputStream(); ByteArrayOutputStream data = new ByteArrayOutputStream(); int len; byte[] buf = new byte[50000]; while ((len = input.read(buf)) > 0) { data.write(buf, 0, len); } conn.disconnect(); String jsonResponse = new String(data.toByteArray(), "UTF-8"); if (responseCode != 200) { throw new IOException(jsonResponse); } logger.debug("callWebService(): jsonResponse:" + jsonResponse); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); T response = mapper.readValue(new StringReader(jsonResponse), clazz); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); sw = new StringWriter(); mapper.writeValue(sw, response); logger.debug( "callWebService(): parsed response into " + response.getClass().getName() + ":" + sw.toString()); return response; }
From source file:com.clueride.auth.Auth0ConnectionImpl.java
@Override public int makeRequest(URL auth0Url, String accessToken) throws IOException { /* Open Connection */ HttpsURLConnection connection = (HttpsURLConnection) auth0Url.openConnection(); /* Provide 'credentials' */ connection.setRequestProperty("Authorization", "Bearer " + accessToken); /* Retrieve response */ responseCode = connection.getResponseCode(); responseMessage = connection.getResponseMessage(); if (responseCode == 200) { InputStream inputStr = connection.getInputStream(); String encoding = connection.getContentEncoding() == null ? "UTF-8" : connection.getContentEncoding(); jsonResponse = IOUtils.toString(inputStr, encoding); LOGGER.debug(String.format("Raw JSON Response:\n%s", jsonResponse)); } else {/*w w w . j a va 2s. c o m*/ LOGGER.error(String.format("Unable to read response: %d %s", responseCode, responseMessage)); } return responseCode; }
From source file:org.mule.modules.wechat.common.HttpsConnection.java
public Map<String, Object> get(String httpsURL) throws Exception { // Setup connection String result = ""; URL url = new URL(httpsURL); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("Content-Type", "application/json; encoding=utf-8"); // Call wechat InputStream ins = con.getInputStream(); InputStreamReader isr = new InputStreamReader(ins, "UTF-8"); BufferedReader in = new BufferedReader(isr); // Read result String inputLine;/*from w ww . j a v a 2 s . c o m*/ StringBuilder sb = new StringBuilder(); while ((inputLine = in.readLine()) != null) { sb.append((new JSONObject(inputLine)).toString()); } result = sb.toString(); in.close(); // Convert JSON string to Map ObjectMapper mapper = new ObjectMapper(); Map<String, Object> map = mapper.readValue(result, new TypeReference<Map<String, Object>>() { }); return map; }
From source file:org.apache.nifi.minifi.c2.integration.test.AbstractTestSecure.java
protected ConfigSchema assertReturnCode(String query, SSLContext sslContext, int expectedReturnCode) throws Exception { HttpsURLConnection httpsURLConnection = openUrlConnection(C2_URL + query, sslContext); try {// w w w. ja v a 2 s .c om assertEquals(expectedReturnCode, httpsURLConnection.getResponseCode()); if (expectedReturnCode == 200) { return SchemaLoader.loadConfigSchemaFromYaml(httpsURLConnection.getInputStream()); } } finally { httpsURLConnection.disconnect(); } return null; }
From source file:com.github.jakz.geophoto.reverse.NominatimReverseGeocodingJAPI.java
private String getJSON(String urlString) throws IOException { URL obj = new URL(urlString); HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) (jack.ngi@gmail.com) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"); InputStream is = conn.getInputStream(); String json = IOUtils.toString(is, "UTF-8"); is.close();/*from ww w . j av a 2s . co m*/ return json; }