List of usage examples for javax.net.ssl HttpsURLConnection setDoOutput
public void setDoOutput(boolean dooutput)
From source file:com.nadmm.airports.notams.NotamService.java
private void fetchNotams(String icaoCode, File notamFile) throws IOException { String params = String.format(NOTAM_PARAM, icaoCode); HttpsURLConnection conn = (HttpsURLConnection) NOTAM_URL.openConnection(); conn.setRequestProperty("Connection", "close"); conn.setDoInput(true);// ww w . j a va 2 s.c o m conn.setDoOutput(true); conn.setUseCaches(false); conn.setConnectTimeout(30 * 1000); conn.setReadTimeout(30 * 1000); conn.setRequestMethod("POST"); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux i686; en-US)"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", Integer.toString(params.length())); // Write out the form parameters as the request body OutputStream faa = conn.getOutputStream(); faa.write(params.getBytes("UTF-8")); faa.close(); int response = conn.getResponseCode(); if (response == HttpURLConnection.HTTP_OK) { // Request was successful, parse the html to extract notams InputStream in = conn.getInputStream(); ArrayList<String> notams = parseNotamsFromHtml(in); in.close(); // Write the NOTAMS to the cache file BufferedOutputStream cache = new BufferedOutputStream(new FileOutputStream(notamFile)); for (String notam : notams) { cache.write(notam.getBytes()); cache.write('\n'); } cache.close(); } }
From source file:xin.nic.sdk.registrar.util.HttpUtil.java
/** * ??HTTPS GET/*from www . ja v a 2s.c o m*/ * * @param url URL * @return */ public static HttpResp doHttpsGet(URL url) { HttpsURLConnection conn = null; InputStream inputStream = null; Reader reader = null; try { // ???httphttps String protocol = url.getProtocol(); if (!PROTOCOL_HTTPS.equals(protocol)) { throw new XinException("xin.error.url", "?https"); } // conn = (HttpsURLConnection) url.openConnection(); SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, tmArr, new SecureRandom()); conn.setSSLSocketFactory(sc.getSocketFactory()); // ? conn.setConnectTimeout(connTimeout); conn.setReadTimeout(readTimeout); conn.setDoOutput(true); conn.setDoInput(true); // UserAgent conn.setRequestProperty("User-Agent", "java-sdk"); // ? conn.connect(); // ? inputStream = conn.getInputStream(); reader = new InputStreamReader(inputStream, charset); BufferedReader bufferReader = new BufferedReader(reader); StringBuilder stringBuilder = new StringBuilder(); String inputLine = ""; while ((inputLine = bufferReader.readLine()) != null) { stringBuilder.append(inputLine); stringBuilder.append("\n"); } // HttpResp resp = new HttpResp(); resp.setStatusCode(conn.getResponseCode()); resp.setStatusPhrase(conn.getResponseMessage()); resp.setContent(stringBuilder.toString()); // return resp; } catch (MalformedURLException e) { throw new XinException("xin.error.url", "url:" + url + ", url?"); } catch (IOException e) { throw new XinException("xin.error.http", String.format("IOException:%s", e.getMessage())); } catch (KeyManagementException e) { throw new XinException("xin.error.url", "url:" + url + ", url?"); } catch (NoSuchAlgorithmException e) { throw new XinException("xin.error.url", "url:" + url + ", url?"); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { throw new XinException("xin.error.url", "url:" + url + ", reader"); } } if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { throw new XinException("xin.error.url", "url:" + url + ", ?"); } } // quietClose(conn); } }
From source file:com.kaixin.connect.Util.java
/** * http//from w w w .j a v a 2s . co m * * @param context * * @param requestURL * * @param httpMethod * GET POST * @param params * key-valuekeyvalueStringbyte[] * @param photos * key-value keyfilename * valueInputStreambyte[] * 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 = Util.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.illusionaryone.GameWispAPI.java
@SuppressWarnings("UseSpecificCatch") private static JSONObject readJsonFromUrl(String methodType, String urlAddress) { JSONObject jsonResult = new JSONObject("{}"); InputStream inputStream = null; OutputStream outputStream = null; URL urlRaw;//from ww w .j av a2 s.c om HttpsURLConnection urlConn; String jsonText = ""; if (sAccessToken.length() == 0) { if (!noAccessWarning) { com.gmt2001.Console.err.println( "GameWispAPI: Attempting to use GameWisp API without key. Disable GameWisp module."); noAccessWarning = true; } JSONStringer jsonObject = new JSONStringer(); return (new JSONObject(jsonObject.object().key("result").object().key("status").value(-1).endObject() .endObject().toString())); } try { urlRaw = new URL(urlAddress); urlConn = (HttpsURLConnection) urlRaw.openConnection(); urlConn.setDoInput(true); urlConn.setRequestMethod(methodType); 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 QuorraBot/2015"); if (methodType.equals("POST")) { urlConn.setDoOutput(true); urlConn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); } else { urlConn.addRequestProperty("Content-Type", "application/json"); } 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); jsonResult = new JSONObject(jsonText); fillJSONObject(jsonResult, true, methodType, urlAddress, urlConn.getResponseCode(), "", "", jsonText); } catch (JSONException ex) { fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "JSONException", ex.getMessage(), jsonText); com.gmt2001.Console.err .println("GameWispAPI::Bad JSON (" + urlAddress + "): " + jsonText.substring(0, 100) + "..."); } catch (NullPointerException ex) { fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "NullPointerException", ex.getMessage(), ""); com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (MalformedURLException ex) { fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "MalformedURLException", ex.getMessage(), ""); com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (SocketTimeoutException ex) { fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "SocketTimeoutException", ex.getMessage(), ""); com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (IOException ex) { fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "IOException", ex.getMessage(), ""); com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (Exception ex) { fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "Exception", ex.getMessage(), ""); com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage()); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException ex) { fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "IOException", ex.getMessage(), ""); com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage()); } } } return (jsonResult); }
From source file:com.ds.kaixin.Util.java
/** * http/* w w w . j a va 2s. c om*/ * * @param context * * @param requestURL * * @param httpMethod * GET POST * @param params * key-valuekeyvalueString * byte[] * @param photos * key-value keyfilename * valueInputStreambyte[] * 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 = Util.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:org.openmrs.module.rheashradapter.util.GenerateORU_R01Alert.java
public String callQueryFacility(String msg, Encounter e) throws IOException, TransformerFactoryConfigurationError, TransformerException { Cohort singlePatientCohort = new Cohort(); singlePatientCohort.addMember(e.getPatient().getId()); Map<Integer, String> patientIdentifierMap = Context.getPatientSetService() .getPatientIdentifierStringsByType(singlePatientCohort, Context.getPatientService() .getPatientIdentifierTypeByName(RHEAHL7Constants.IDENTIFIER_TYPE)); // Setup connection String id = patientIdentifierMap.get(patientIdentifierMap.keySet().iterator().next()); URL url = new URL(hostname + "/ws/rest/v1/alerts"); System.out.println("full url " + url); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setDoInput(true);//from w ww. jav a 2s .c o m // This is important to get the connection to use our trusted // certificate conn.setSSLSocketFactory(sslFactory); addHTTPBasicAuthProperty(conn); // conn.setConnectTimeout(timeOut); OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); log.error("body" + msg); out.write(msg); out.close(); conn.connect(); String headerValue = conn.getHeaderField("http.status"); // Test response code if (conn.getResponseCode() != 200) { throw new IOException(conn.getResponseMessage()); } String result = convertInputStreamToString(conn.getInputStream()); conn.disconnect(); return result; }
From source file:org.openmrs.module.rheapocadapter.handler.ConnectionHandler.java
public String[] callPostAndPut(String stringUrl, String body, String method) { try {/*from ww w. jav a 2 s . c o m*/ // Setup connection URL url = new URL(stringUrl); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod(method.toUpperCase()); conn.setDoInput(true); // This is important to get the connection to use our trusted // certificate conn.setSSLSocketFactory(sslFactory); addHTTPBasicAuthProperty(conn); conn.setConnectTimeout(timeOut); // bug fixing for SSL error, this is a temporary fix, need to find a // long term one conn.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); log.error("body" + body); out.write(body); out.close(); conn.connect(); String result = ""; int code = conn.getResponseCode(); if (code == 201) { result = "Saved succefully"; } else { result = "Not Saved"; } conn.disconnect(); return new String[] { code + "", result }; } catch (MalformedURLException e) { e.printStackTrace(); log.error("MalformedURLException while callPostAndPut " + e.getMessage()); return new String[] { 400 + "", e.getMessage() }; } catch (IOException e) { e.printStackTrace(); log.error("IOException while callPostAndPut " + e.getMessage()); return new String[] { 600 + "", e.getMessage() }; } }
From source file:br.com.intelidev.dao.userDao.java
/** * Run the web service request// ww w . j a v a 2s . c o m * @param username * @param password * @return */ public boolean login_acess(String username, String password) { HttpsURLConnection conn = null; boolean bo_return = false; try { // Create url to the Device Cloud server for a given web service request URL url = new URL("https://devicecloud.digi.com/ws/sci"); conn = (HttpsURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("GET"); // Build authentication string String userpassword = username + ":" + password; // can change this to use a different base64 encoder String encodedAuthorization = Base64.encodeBase64String(userpassword.getBytes()).trim(); // set request headers conn.setRequestProperty("Authorization", "Basic " + encodedAuthorization); // Get input stream from response and convert to String InputStream is = conn.getInputStream(); Scanner isScanner = new Scanner(is); StringBuffer buf = new StringBuffer(); while (isScanner.hasNextLine()) { buf.append(isScanner.nextLine() + "\n"); } //String responseContent = buf.toString(); // add line returns between tags to make it a bit more readable //responseContent = responseContent.replaceAll("><", ">\n<"); // Output response to standard out //System.out.println(responseContent); bo_return = true; } catch (Exception e) { // Print any exceptions that occur System.out.println("br.com.intelidev.dao.userDao.login_acess() Error: " + e); bo_return = false; //e.printStackTrace(); } finally { if (conn != null) conn.disconnect(); if (bo_return) { System.out.println("Conectou "); } else { System.out.println("No conectou "); } } return bo_return; }
From source file:org.georchestra.console.ReCaptchaV2.java
/** * * @param url//from w ww . j av a 2 s .co m * @param privateKey * @param gRecaptchaResponse * * @return true if validaded on server side by google, false in case of error or if an exception occurs */ public boolean isValid(String url, String privateKey, String gRecaptchaResponse) { boolean isValid = false; try { URL obj = new URL(url); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); // add request header con.setRequestMethod("POST"); String postParams = "secret=" + privateKey + "&response=" + gRecaptchaResponse; // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(postParams); wr.flush(); wr.close(); if (LOG.isDebugEnabled()) { int responseCode = con.getResponseCode(); LOG.debug("\nSending 'POST' request to URL : " + url); LOG.debug("Post parameters : " + postParams); LOG.debug("Response Code : " + responseCode); } // getResponse 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 LOG.debug(response.toString()); JSONObject captchaResponse; try { captchaResponse = new JSONObject(response.toString()); if (captchaResponse.getBoolean("success")) { isValid = true; } else { // Error in response LOG.info("The user response to recaptcha is not valid. The error message is '" + captchaResponse.getString("error-codes") + "' - see Error Code Reference at https://developers.google.com/recaptcha/docs/verify."); } } catch (JSONException e) { // Error in response LOG.error("Error while parsing ReCaptcha JSON response", e); } } catch (IOException e) { LOG.error("An error occured when trying to contact google captchaV2", e); } return isValid; }
From source file:cn.bidaround.ytcore.kaixin.KaixinUtil.java
/** * ??http//w w w . j ava 2s. c o m * * @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; }