List of usage examples for javax.net.ssl HttpsURLConnection getResponseCode
public int getResponseCode() throws IOException
From source file:edu.hackathon.perseus.core.httpSpeedTest.java
public void sendPost() throws Exception { String url = "https://selfsolve.apple.com/wcResults.do"; URL obj = new URL(url); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345"; // Send post request con.setDoOutput(true);//from w w w.j av a 2 s . co m DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); 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 System.out.println(response.toString()); }
From source file:com.emuneee.nctrafficcams.tasks.GetLatestCameras.java
private String getLatestUpdateTime() { HttpsURLConnection connection = null; BufferedReader reader = null; String updateDatetime = null; try {//from w ww. java2 s . c o m StringBuilder updateStr = new StringBuilder(); connection = HttpUtils.getAuthUrlConnection(mBaseUrl + sUpdatePath, mContext); reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { updateStr.append(line); } Log.d(TAG, "Content Size: " + updateStr.length()); Log.d(TAG, "Response Code: " + connection.getResponseCode()); JSONObject updateObj = new JSONObject(updateStr.toString()); updateDatetime = updateObj.getString("updated"); } catch (Exception e) { Log.e(TAG, "Error getting latest update time"); Log.e(TAG, e.getMessage()); } finally { if (connection != null) { connection.disconnect(); } if (reader != null) { try { reader.close(); } catch (IOException e) { Log.w(TAG, "Error retrieving latest update time"); Log.w(TAG, e.getMessage()); } } } return updateDatetime; }
From source file:in.rab.ordboken.NeClient.java
private void loginMainSite() throws IOException, LoginException { ArrayList<BasicNameValuePair> data = new ArrayList<BasicNameValuePair>(); data.add(new BasicNameValuePair("_save_loginForm", "true")); data.add(new BasicNameValuePair("redir", "/success")); data.add(new BasicNameValuePair("redirFail", "/fail")); data.add(new BasicNameValuePair("userName", mUsername)); data.add(new BasicNameValuePair("passWord", mPassword)); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(data); URL url = new URL("https://www.ne.se/user/login.jsp"); HttpsURLConnection https = (HttpsURLConnection) url.openConnection(); https.setInstanceFollowRedirects(false); https.setFixedLengthStreamingMode((int) entity.getContentLength()); https.setDoOutput(true);//w w w .j a v a 2s.co m try { OutputStream output = https.getOutputStream(); entity.writeTo(output); output.close(); Integer response = https.getResponseCode(); if (response != 302) { throw new LoginException("Unexpected response: " + response); } String location = https.getHeaderField("Location"); if (!location.contains("/success")) { throw new LoginException("Failed to login"); } } finally { https.disconnect(); } }
From source file:org.whispersystems.textsecure.push.PushServiceSocket.java
private void uploadExternalFile(String method, String url, byte[] data) throws IOException { URL uploadUrl = new URL(url); HttpsURLConnection connection = (HttpsURLConnection) uploadUrl.openConnection(); connection.setDoOutput(true);/*from w ww. j a v a 2 s. c om*/ connection.setRequestMethod(method); connection.setRequestProperty("Content-Type", "application/octet-stream"); connection.connect(); try { OutputStream out = connection.getOutputStream(); out.write(data); out.close(); if (connection.getResponseCode() != 200) { throw new IOException( "Bad response: " + connection.getResponseCode() + " " + connection.getResponseMessage()); } } finally { connection.disconnect(); } }
From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.serverconnection.impl.HttpTransportImpl.java
@Override public String execute(String request, int connectTimeout, int readTimeout) { // NOTE: We will only show exceptions in the debug level, because they will be handled in the checkConnection() // method and this changes the bridge state. If a command was send it fails than and a sensorJob will be // execute the next time, by TimeOutExceptions. By other exceptions the checkConnection() method handles it in // max 1 second. String response = null;//w w w .jav a2 s . co m HttpsURLConnection connection = null; try { String correctedRequest = checkSessionToken(request); connection = getConnection(correctedRequest, connectTimeout, readTimeout); if (connection != null) { connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_FORBIDDEN) { if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) { response = IOUtils.toString(connection.getErrorStream()); } else { response = IOUtils.toString(connection.getInputStream()); } if (response != null) { if (!response.contains("Authentication failed")) { if (loginCounter > 0) { connectionManager.checkConnection(responseCode); } loginCounter = 0; } else { connectionManager.checkConnection(ConnectionManager.AUTHENTIFICATION_PROBLEM); loginCounter++; } } } connection.disconnect(); if (response == null && connectionManager != null && loginCounter <= MAY_A_NEW_SESSION_TOKEN_IS_NEEDED) { if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) { execute(addSessionToken(correctedRequest, connectionManager.getNewSessionToken()), connectTimeout, readTimeout); loginCounter++; } else { connectionManager.checkConnection(responseCode); loginCounter++; return null; } } return response; } } catch (SocketTimeoutException e) { informConnectionManager(ConnectionManager.SOCKET_TIMEOUT_EXCEPTION); } catch (java.net.ConnectException e) { informConnectionManager(ConnectionManager.CONNECTION_EXCEPTION); } catch (MalformedURLException e) { informConnectionManager(ConnectionManager.MALFORMED_URL_EXCEPTION); } catch (java.net.UnknownHostException e) { informConnectionManager(ConnectionManager.UNKNOWN_HOST_EXCEPTION); } catch (IOException e) { logger.error("An IOException occurred: ", e); if (connectionManager != null) { informConnectionManager(ConnectionManager.GENERAL_EXCEPTION); } } finally { if (connection != null) { connection.disconnect(); } } return null; }
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 ww w .ja va2s. co m*/ 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.gmt2001.TwitchAPIv2.java
private JSONObject GetData(request_type type, String url, String post, String oauth) { JSONObject j = new JSONObject(); try {//www. j a v a2 s . c om URL u = new URL(url); HttpsURLConnection c = (HttpsURLConnection) u.openConnection(); c.addRequestProperty("Accept", header_accept); if (!clientid.isEmpty()) { c.addRequestProperty("Client-ID", clientid); } if (!oauth.isEmpty()) { c.addRequestProperty("Authorization", "OAuth " + oauth); } c.setRequestMethod(type.name()); c.setUseCaches(false); c.setDefaultUseCaches(false); c.setConnectTimeout(timeout); c.connect(); if (!post.isEmpty()) { IOUtils.write(post, c.getOutputStream()); } String content; if (c.getResponseCode() == 200) { content = IOUtils.toString(c.getInputStream(), c.getContentEncoding()); } else { content = IOUtils.toString(c.getErrorStream(), c.getContentEncoding()); } j = new JSONObject(content); j.put("_success", true); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", c.getResponseCode()); j.put("_exception", ""); j.put("_exceptionMessage", ""); } catch (MalformedURLException ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_exception", "MalformedURLException"); j.put("_exceptionMessage", ex.getMessage()); } catch (SocketTimeoutException ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_exception", "SocketTimeoutException"); j.put("_exceptionMessage", ex.getMessage()); } catch (IOException ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_exception", "IOException"); j.put("_exceptionMessage", ex.getMessage()); } catch (Exception ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_exception", "Exception [" + ex.getClass().getName() + "]"); j.put("_exceptionMessage", ex.getMessage()); } return j; }
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);//from w w w . j a v a2s . c om conn.setRequestMethod("POST"); conn.setDoInput(true); // 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.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); }/* ww w . ja v a 2 s . c o m*/ 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:httpRequests.GetPost.java
private void sendPost() throws Exception { String url = "https://selfsolve.apple.com/wcResults.do"; URL obj = new URL(url); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345"; // Send post request con.setDoOutput(true);/*w w w .j a va 2 s .c o m*/ DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); 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 System.out.println(response.toString()); }