List of usage examples for javax.net.ssl HttpsURLConnection setRequestProperty
public void setRequestProperty(String key, String value)
From source file:org.wso2.carbon.automation.test.utils.http.client.HttpsURLConnectionClient.java
public static HttpsResponse postWithBasicAuth(String uri, String requestQuery, String userName, String password) throws IOException { if (uri.startsWith("https://")) { URL url = new URL(uri); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setRequestMethod("POST"); String encode = new String( new org.apache.commons.codec.binary.Base64().encode((userName + ":" + password).getBytes())) .replaceAll("\n", ""); ;//from w w w .j a va 2s.c om conn.setRequestProperty("Authorization", "Basic " + encode); conn.setDoOutput(true); // Triggers POST. conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("charset", "utf-8"); conn.setRequestProperty("Content-Length", "" + Integer.toString(requestQuery.getBytes().length)); conn.setUseCaches(false); conn.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(requestQuery); conn.setReadTimeout(10000); conn.connect(); System.out.println(conn.getRequestMethod()); // Get the response StringBuilder sb = new StringBuilder(); BufferedReader rd = null; try { rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.defaultCharset())); String line; while ((line = rd.readLine()) != null) { sb.append(line); } return new HttpsResponse(sb.toString(), conn.getResponseCode()); } catch (FileNotFoundException ignored) { } finally { if (rd != null) { rd.close(); } wr.flush(); wr.close(); conn.disconnect(); } } return null; }
From source file:com.illusionaryone.GitHubAPIv3.java
@SuppressWarnings("UseSpecificCatch") private static JSONObject readJsonFromUrl(String urlAddress, boolean isArray) { JSONObject jsonResult = new JSONObject("{}"); InputStream inputStream = null; URL urlRaw;//from ww w . j av a 2 s. c om HttpsURLConnection urlConn; String jsonText = ""; try { urlRaw = new URL(urlAddress); urlConn = (HttpsURLConnection) urlRaw.openConnection(); urlConn.setDoInput(true); urlConn.setRequestMethod("GET"); urlConn.addRequestProperty("Content-Type", "application/json"); urlConn.addRequestProperty("Accept", "application/vnd.github.v3+json"); urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015"); urlConn.connect(); if (urlConn.getResponseCode() == 200) { inputStream = urlConn.getInputStream(); } else { inputStream = urlConn.getErrorStream(); } BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8"))); jsonText = readAll(rd); if (isArray) { jsonResult = new JSONObject("{ \"array\": " + jsonText + " }"); } else { jsonResult = new JSONObject(jsonText); } fillJSONObject(jsonResult, true, "GET", urlAddress, urlConn.getResponseCode(), "", "", jsonText); } catch (JSONException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "JSONException", ex.getMessage(), jsonText); com.gmt2001.Console.err.println("GitHubv3API::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (NullPointerException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "NullPointerException", ex.getMessage(), ""); com.gmt2001.Console.err.println("GitHubv3API::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (MalformedURLException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "MalformedURLException", ex.getMessage(), ""); com.gmt2001.Console.err.println("GitHubv3API::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (SocketTimeoutException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "SocketTimeoutException", ex.getMessage(), ""); com.gmt2001.Console.err.println("GitHubv3API::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (IOException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), ""); com.gmt2001.Console.err.println("GitHubv3API::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (Exception ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "Exception", ex.getMessage(), ""); com.gmt2001.Console.err.println("GitHubv3API::readJsonFromUrl::Exception: " + ex.getMessage()); } finally { if (inputStream != null) try { inputStream.close(); } catch (IOException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), ""); com.gmt2001.Console.err.println("GitHubv3API::readJsonFromUrl::Exception: " + ex.getMessage()); } } return (jsonResult); }
From source file:com.raphfrk.craftproxyclient.net.auth.AuthManager.java
@SuppressWarnings("unchecked") public static void authServer17(String hash) throws IOException { URL url;// ww w. j av a2 s . com String username; String accessToken; try { if (loginDetails == null) { throw new IOException("Not logged in"); } try { username = URLEncoder.encode(getUsername(), "UTF-8"); accessToken = URLEncoder.encode(getAccessToken(), "UTF-8"); hash = URLEncoder.encode(hash, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IOException("Username/password encoding error", e); } String urlString; urlString = sessionServer17; url = new URL(urlString); } catch (MalformedURLException e) { throw new IOException("Auth server URL error", e); } HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setDoOutput(true); con.setInstanceFollowRedirects(false); con.setReadTimeout(5000); con.setConnectTimeout(5000); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/json"); con.connect(); JSONObject obj = new JSONObject(); obj.put("accessToken", accessToken); obj.put("selectedProfile", loginDetails.get("selectedProfile")); obj.put("serverId", hash); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(con.getOutputStream(), StandardCharsets.UTF_8)); try { obj.writeJSONString(writer); writer.flush(); writer.close(); } catch (IOException e) { if (writer != null) { writer.close(); con.disconnect(); return; } } if (con.getResponseCode() != 200) { throw new IOException("Unable to verify username, please restart proxy"); } BufferedReader reader = new BufferedReader( new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8)); try { String reply = reader.readLine(); if (reply != null) { throw new IOException("Auth server replied (" + reply + ")"); } } finally { reader.close(); con.disconnect(); } }
From source file:org.liberty.android.fantastischmemo.downloader.quizlet.lib.java
private static String makePostApiCall(URL url, String content, String authToken) throws IOException { HttpsURLConnection conn = null; OutputStreamWriter writer = null; String res = ""; try {//from w ww .jav a 2 s.c o m conn = (HttpsURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.addRequestProperty("Authorization", "Bearer " + authToken); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(content); writer.close(); if (conn.getResponseCode() / 100 >= 3) { Log.v("makePostApiCall", "Post content is: " + content); String error = ""; try { JsonReader r = new JsonReader(new InputStreamReader(conn.getErrorStream(), "UTF-8")); r.beginObject(); while (r.hasNext()) { error += r.nextName() + ": " + r.nextString() + "\r\n"; } r.endObject(); r.close(); } catch (Throwable eex) { } Log.v("makePostApiCall", "Error string is: " + error); res = error; throw new IOException( "Response code: " + conn.getResponseCode() + " URL is: " + url + " \nError: " + error); } else { JsonReader r = new JsonReader(new InputStreamReader(conn.getInputStream())); r.beginObject(); while (r.hasNext()) { try { res += r.nextName() + ": " + r.nextString() + "\n"; } catch (Exception ex) { r.skipValue(); } } return res; } } finally { conn.disconnect(); //return res; } }
From source file:com.raphfrk.craftproxyclient.net.auth.AuthManager.java
public static JSONObject sendRequest(JSONObject request, String endpoint) { URL url;/* w w w . ja va 2 s.co m*/ try { url = new URL(authServer + "/" + endpoint); } catch (MalformedURLException e) { return null; } try { HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setDoOutput(true); con.setInstanceFollowRedirects(false); con.setReadTimeout(5000); con.setConnectTimeout(5000); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/json"); con.connect(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(con.getOutputStream(), StandardCharsets.UTF_8)); try { request.writeJSONString(writer); writer.flush(); writer.close(); if (con.getResponseCode() != 200) { return null; } BufferedReader reader = new BufferedReader( new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8)); try { JSONParser parser = new JSONParser(); try { return (JSONObject) parser.parse(reader); } catch (ParseException e) { return null; } } finally { reader.close(); } } finally { writer.close(); con.disconnect(); } } catch (IOException e) { e.printStackTrace(); return null; } }
From source file:Main.IrcBot.java
public static void postGit(String pasteBinSnippet, PrintWriter out) { try {/*ww w . j a v a2s.c om*/ 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.scaniatv.ChallongeAPI.java
/** * @function readJsonFromUrl/*ww w .jav a 2 s . c o m*/ * * @param {String} urlAddress */ @SuppressWarnings("UseSpecificCatch") private static JSONObject readJsonFromUrl(String urlAddress, boolean isArray) { JSONObject jsonResult = new JSONObject("{}"); InputStream inputStream = null; URL urlRaw; HttpsURLConnection urlConn; String jsonText = ""; try { urlRaw = new URL(urlAddress); urlConn = (HttpsURLConnection) urlRaw.openConnection(); urlConn.setDoInput(true); urlConn.setRequestMethod("GET"); urlConn.addRequestProperty("Content-Type", "application/json"); urlConn.addRequestProperty("Accept", "application/vnd.github.v3+json"); urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015"); urlConn.connect(); if (urlConn.getResponseCode() == 200) { inputStream = urlConn.getInputStream(); } else { inputStream = urlConn.getErrorStream(); } BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8"))); jsonText = readAll(rd); if (isArray) { jsonResult = new JSONObject("{ \"array\": " + jsonText + " }"); } else { jsonResult = new JSONObject(jsonText); } fillJSONObject(jsonResult, true, "GET", urlAddress, urlConn.getResponseCode(), "", "", jsonText); } catch (JSONException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "JSONException", ex.getMessage(), jsonText); com.gmt2001.Console.err.println("ChallongeAPI::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (NullPointerException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "NullPointerException", ex.getMessage(), ""); com.gmt2001.Console.err.println("ChallongeAPI::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (MalformedURLException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "MalformedURLException", ex.getMessage(), ""); com.gmt2001.Console.err.println("ChallongeAPI::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (SocketTimeoutException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "SocketTimeoutException", ex.getMessage(), ""); com.gmt2001.Console.err.println("ChallongeAPI::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (IOException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), ""); com.gmt2001.Console.err.println("ChallongeAPI::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (Exception ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "Exception", ex.getMessage(), ""); com.gmt2001.Console.err.println("ChallongeAPI::readJsonFromUrl::Exception: " + ex.getMessage()); } finally { if (inputStream != null) try { inputStream.close(); } catch (IOException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), ""); com.gmt2001.Console.err.println("ChallongeAPI::readJsonFromUrl::Exception: " + ex.getMessage()); } } return (jsonResult); }
From source file:com.camel.trainreserve.JDKHttpsClient.java
public static String doPost(String url, String cookieStr, String ctype, byte[] content, int connectTimeout, int readTimeout) throws Exception { HttpsURLConnection conn = null; OutputStream out = null;//from ww w. j av a 2 s . c o m String rsp = null; try { try { SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null, new TrustManager[] { new DefaultTrustManager() }, new SecureRandom()); //SSLContext.setDefault(ctx); conn = getConnection(new URL(url), METHOD_POST, ctype); conn.setSSLSocketFactory(ctx.getSocketFactory()); conn.setRequestProperty("Cookie", cookieStr); conn.setHostnameVerifier(new TrustAnyHostnameVerifier()); conn.setConnectTimeout(connectTimeout); conn.setReadTimeout(readTimeout); } catch (Exception e) { log.error("GET_CONNECTOIN_ERROR, URL = " + url, e); throw e; } try { out = conn.getOutputStream(); out.write(content); rsp = getResponseAsString(conn); } catch (IOException e) { log.error("REQUEST_RESPONSE_ERROR, URL = " + url, e); throw e; } } finally { if (out != null) { out.close(); } if (conn != null) { conn.disconnect(); } } return rsp; }
From source file:Main.java
/** * * @param url - String/*from w w w . j ava 2 s .c o m*/ * @param reqParam refer POST method * @param accessToken - String * @return ArrayList<String> 0: responseBody * 1: responseCode */ public static ArrayList<String> getResponse(String url, String reqParam, String accessToken) { StringBuilder response = null; StringBuilder urlBuilder = null; BufferedReader in = null; HttpsURLConnection con = null; ArrayList<String> responseList = new ArrayList<String>(); int responseCode = -1; try { response = new StringBuilder(); urlBuilder = new StringBuilder(); urlBuilder.append(url); urlBuilder.append("?").append(reqParam); urlBuilder.append("&access_token=").append(accessToken); URL urlObj = new URL(urlBuilder.toString()); con = (HttpsURLConnection) urlObj.openConnection(); con.setRequestMethod("GET"); con.setDoInput(true); con.setDoOutput(false); con.setRequestProperty("Authorization: Bearer", accessToken); in = new BufferedReader(new InputStreamReader(con.getInputStream())); responseCode = con.getResponseCode(); String inputLine = ""; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } } catch (Exception e) { in = new BufferedReader(new InputStreamReader(con.getErrorStream())); String inputLine = ""; try { while ((inputLine = in.readLine()) != null) { response.append(inputLine); } } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if (responseCode == -1) { } else { System.out.println(response.toString()); } } finally { try { in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } responseList.add(response.toString()); responseList.add(String.valueOf(responseCode)); return responseList; }
From source file:com.gson.util.HttpKit.java
/** * ?http?/*from ww w.j av a 2 s . co m*/ * @param url * @param method * @return * @throws IOException * @throws NoSuchAlgorithmException * @throws NoSuchProviderException * @throws KeyManagementException */ private static HttpsURLConnection initHttps(String url, String method, Map<String, String> headers) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException { TrustManager[] tm = { new MyX509TrustManager() }; System.setProperty("https.protocols", "SSLv3"); SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); // SSLContextSSLSocketFactory SSLSocketFactory ssf = sslContext.getSocketFactory(); URL _url = new URL(url); HttpsURLConnection http = (HttpsURLConnection) _url.openConnection(); // ?? http.setHostnameVerifier(new HttpKit().new TrustAnyHostnameVerifier()); // http.setConnectTimeout(25000); // ? --?? http.setReadTimeout(25000); http.setRequestMethod(method); http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); http.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36"); if (null != headers && !headers.isEmpty()) { for (Entry<String, String> entry : headers.entrySet()) { http.setRequestProperty(entry.getKey(), entry.getValue()); } } http.setSSLSocketFactory(ssf); http.setDoOutput(true); http.setDoInput(true); http.connect(); return http; }