Reading an X509 certificate in Java can be done using the following code. I used it specifically for obtaining a reference to the Apple WWDR certificate, but generally speaking, this will work for reading any certificate in X509 format.
import java.security.cert.*;
import java.io.*;
import org.apache.commons.io.IOUtils;
import java.security.NoSuchProviderException;
import java.security.NoSuchAlgorithmException;
import java.security.KeyStoreException;
public static X509Certificate readWWDRCertificate(String keyFile) throws IOException, KeyStoreException, NoSuchProviderException, NoSuchAlgorithmException, CertificateException
{
FileInputStream fis = null;
ByteArrayInputStream bais = null;
try
{
// use FileInputStream to read the file
fis = new FileInputStream(keyFile);
// read the bytes
byte value[] = new byte[fis.available()];
fis.read(value);
bais = new ByteArrayInputStream(value);
// get X509 certificate factory
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
// certificate factory can now create the certificate
return (X509Certificate)certFactory.generateCertificate(bais);
}
finally
{
IOUtils.closeQuietly(fis);
IOUtils.closeQuietly(bais);
}
}
The parameter you pass in should be the absolute location of the certificate file. In my case, my String parameter is something like "C:\\cert\AppleWWDRCA.cer".
Points of interest, usually heavily influenced by technology, gadgets and programming.
Showing posts with label java. Show all posts
Showing posts with label java. Show all posts
Friday, 14 September 2012
Tuesday, 6 December 2011
Android - Get body of HTTP Response as String
Making HTTP requests in Android often results in the same type of boiler plate code being produced. One in particular that annoys me is having to get the response body as in InputStream and using BufferedReader and the likes.
Bundled along with Android is the org.apache.http libraries, which provide classes for easy interaction for common HTTP-related activities.
The following snippet shows how to perform an HTTP GET on a URI, and turn the response body into a string. In my case, I take the string and turn into a JSON object, but you might parse as XML or whatever.
DefaultHttpClient http = new DefaultHttpClient();
HttpGet httpMethod = new HttpGet();
httpMethod.setURI(new URI(SERVER_URI_GOES_HERE));
HttpResponse response = http.execute(httpMethod);
int responseCode = response.getStatusLine().getStatusCode();
switch(responseCode)
{
case 200:
HttpEntity entity = response.getEntity();
if(entity != null)
{
String responseBody = EntityUtils.toString(entity);
}
break;
}
Labels:
android,
android development,
convert InputStream to String,
entity,
get,
get body as string,
http request,
http response,
http response body,
inputstream,
java,
parse response body,
sdk
Subscribe to:
Posts (Atom)