Software Blog‎ > ‎

HttpsURLConnection Send/Receive Example

posted Apr 21, 2011, 8:12 AM by Nicholas Padilla   [ updated Apr 21, 2011, 10:35 AM ]
Good example of how to create and user a HTTPS connection in JAVA6.  Also shows how you can get at the response and utilize it.

Connection Example

		InputStreamReader streamReader = null;
		OutputStream out = null;
		HttpsURLConnection connection = null;
		BufferedReader bufferedReader = null;
		StringBuffer stringBuffer = new StringBuffer()		
                try {
			String urlString = "https://" + givenURL;
			
                        // add a security provider to system for https call
			Security.addProvider(new Provider());
                        // Create a Hostname Verifier that will validate the URL
                        // important since the connection will not work w/out this
			HostnameVerifier verifier = new HostnameVerifier() {
				@Override
				public boolean verify(String arg0, SSLSession arg1) {
					System.out.println("Url Host : "+arg0+" vs. "+arg1.getPeerHost());
					return true;
				}
			};
			// sets the hostname verifier
			HttpsURLConnection.setDefaultHostnameVerifier( verifier);
			HttpsURLConnection.setFollowRedirects(false);

			String usernamePass = "Username" + ":" + "Password";
			String encoding = new BASE64Encoder().encode (usernamePass.getBytes());

			URL url = new URL(urlString);
			connection = (HttpsURLConnection)url.openConnection();
                        // set basic request properties
			connection.setRequestProperty("Authorization", "Basic "+encoding);
			connection.addRequestProperty("User-Agent", "Some User Agent Id");
                        // xml content type, change if you are not sending an xml request.
			connection.addRequestProperty("Content-Type", "application/xml; charset=utf-8");
			connection.setRequestMethod("POST");
			connection.setDoOutput(true);
			connection.setInstanceFollowRedirects(false);

			out = connection.getOutputStream();
			out.write( "request string here"  ); 
			out.flush(); 
			out.close(); 

			int responseCode = connection.getResponseCode(); 
			String responseMsg = connection.getResponseMessage(); 			

			if(responseCode == 200){

				InputStream is = connection.getInputStream(); 
				streamReader = new InputStreamReader(is);
			        bufferedReader = new BufferedReader(streamReader);
			        String inputLine;
			    
			        while ((inputLine = bufferedReader.readLine()) != null){
			    	    stringBuffer.append(inputLine);
			        }
			        System.out.println(stringBuffer.toString());
			}else{
				throw new IllegalStateException("Should retry operation.");	
			}
		} catch (IOException e) {			
			e.printStackTrace();
		}finally{
			if(connection != null){
				connection.disconnect();
			}
			try {
				if(streamReader != null){
					streamReader.close();
				}
				if(out != null){
					out.close();
				}
				if(bufferedReader != null){
					bufferedReader.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}			
		}

Comments