getting XML data via https:// - java

My code works for http, but not https. Here is the error message im getting when i call getMessage() on the IOException:
java.net.SocketException: Address family not supported by protocol
heres my code:
package com.evankimia;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class XMLParserTestActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
{
Log.e("sys",""+getXML());
}
}
public String getXML(){
String line = null;
try {
DefaultHttpClient httpClient = this.createHttpClient();
HttpPost httpPost = new HttpPost("https://web2.uconn.edu/driver/old/timepoints.php?stopid=10");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
line = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
line = "<results status=\"error\"><msg>Cans't connect to server</msg></results>";
} catch (MalformedURLException e) {
line = "<results status=\"error\"><msg>Cand't connect to server</msg></results>";
} catch (IOException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
e.getMessage();
}
return line;
}
private DefaultHttpClient createHttpClient()
{
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
HttpProtocolParams.setUseExpectContinue(params, true);
SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
return new DefaultHttpClient(conMgr, params);
}
}

The method you listed only works for http. Make your program identify https url and use some thign like following.
/**
* Initialize the HTTP/S connection (if needed)
*
* #param keystoreFile the full path of the keystore file
* #param keystorePass the password for the keystore file
*/
private void initHttps(String keystoreFile, String keystorePass)
{
// check if the URL uses HTTP/S
if (url.toLowerCase().startsWith(HTTPS_PROTOCOL))
{
print("Initializing HTTP/S protocol...");
// set the system properties needed for HTTP/S
System.setProperty("javax.net.ssl.keyStore", keystoreFile);
System.setProperty("javax.net.ssl.keyStorePassword", keystorePass);
System.setProperty("javax.net.ssl.keyStoreType", "JKS");
System.setProperty("javax.net.ssl.trustStore", keystoreFile);
System.setProperty("javax.net.ssl.trustStorePassword", keystorePass);
System.setProperty("javax.protocol.handler.pkgs",
"com.sun.net.ssl.internal.www.protocol");
//int addProvider = Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier()
{ // fix a HTTP/S handshake issue
public boolean verify(String hostName, SSLSession session)
{ // Verify that the host name is acceptable
return true;
}
});
}
}

Related

How to send https post request to with parameter to an api

I'm trying to send https post request to my api that send json response, this is a search function so it will require 1 parameter, but i cannot get the expected result from my api, here are my code
Handler.java
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
public class Handler {
static InputStream is = null;
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public Handler(){
}
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
public String makeServiceCall(String url, int method, List<NameValuePair> params){
try {
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
HttpParams params2 = new BasicHttpParams();
SingleClientConnManager mgr = new SingleClientConnManager(params2, schemeRegistry);
DefaultHttpClient httpClient = new DefaultHttpClient(mgr, params2);
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
if(method == POST){
HttpPost httpPost = new HttpPost(url);
if(params != null){
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
sb.append(line + "\n");
}
is.close();
response = sb.toString();
} catch (Exception e){
Log.e("Buffer Error", "Error : " + e.toString());
}
return response;
}
makeServiceCall is used to make the request to url, but it only works with GET request and couldnt work with POST request, how do i fix this?

Java Refreshing Auth token after 30 min

I want to know how to keep refreshing token every 30 min. Currently i dont have it. I need to cache that token for 30 min and then replace current token with the new refresh token.
Right now when i pass 1000 records all records uses same Auth token but the program runs more than 1 hour. I get Auth token expired error for some of the records.
Can anyone help me with how to handle that scenario ?
Thanks in advance
This is call class and will be calling token class.
package main.java.com.test;
import java.io.IOException;
import java.io.PrintStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;
import org.apache.pig.EvalFunc;
import org.apache.pig.data.Tuple;
import com.google.common.base.Stopwatch;
public class Call {
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws IOException
{
new Call().execute();
}
public String execute() throws IOException {
String number = "01";
String id = "0123456789";
String cd = "107BC0000X";
Token getToken = new Token();
String token = null;
try {
token = getToken.Token();
} catch (Exception e1) {
e1.printStackTrace();
}
System.out.println("access token" + token);
return token;
}
}
This is another class called Token
package main.java.com.test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.codehaus.jettison.json.JSONObject;
public class Token {
private final String USER_AGENT = "Mozilla/5.0";
public String Token() throws Exception
{
Token http = new Token();
http.sendGet();
String token = http.sendPost();
return token;
}
private String sendPost() throws Exception
{
String url = "https://YOUR_AUTH0_DOMAIN/oauth/token";
HttpClient client = new DefaultHttpClient();
HttpClient httpClient1 = wrapClient(client);
HttpPost post = new HttpPost(url);
post.setHeader("User-Agent" , "Mozilla/5.0");
List urlParam = (List) new ArrayList();
urlParam.add(new BasicNameValuePair("client_id", ""));
urlParam.add(new BasicNameValuePair("grant_type", ""));
urlParam.add(new BasicNameValuePair("client_secret", ""));
post.setEntity(new UrlEncodedFormEntity(urlParam));
HttpResponse response = httpClient1.execute(post);
BufferedReader rd = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null){
result.append(line);
}
String[] JsonTags0 = result.toString().split(",");
String[] JsonTags1 = result.toString().split(":");
String token1 = JsonTags1[1].trim();
return token1.substring(1,37);
}
private void sendGet()
{
}
public static HttpClient wrapClient(HttpClient base)
{
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager1();
ctx.init(null, new TrustManager[] {tm},null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
ClientConnectionManager ccm = base.getConnectionManager(ctx , SSLSocketFactory , ALLOW_ALL_HOSTNAME_VERIFIER);
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", ssf , 443));
return new DefaultHttpClient(ccm, base.getParams());
}
catch (Exception ex){
ex.printStackTrace();
return null;
}
}
}

ClassNotFoundException on org.apache.http.ssl.TrustStrategy

I'm trying to run a plugin that makes HTTP/HTTPS POST requests. On it its declared the needed dependencies, that is httpclient and httpcore. I'm using versions 4.5.3 and 4.4.6 respectively. Although imported correctly all (I mean), I got this error on execution time:
Caused by: java.lang.NoClassDefFoundError:
org/apache/http/ssl/TrustStrategy
25.06 19:59:12 [Server] INFO at
com.b5team.postrequest.Main.onCommand(Main.java:77) ~[?:?]
25.06 19:59:12 [Server] INFO at
org.bukkit.command.PluginCommand.execute(PluginCommand.java:44) ~
[Spigot.jar:git-Spigot-3fb9445-6e3cec8]
25.06 19:59:12 [Server] INFO ... 10 more
25.06 19:59:12 [Server] INFO Caused by:
java.lang.ClassNotFoundException: org.apache.http.ssl.TrustStrategy
And here is my code:
package com.b5team.postrequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
public class SocketPOSTRequest {
public void sendRequest(String myurl, String hash, String args[]) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, ClientProtocolException, IOException {
HttpClientBuilder b = HttpClientBuilder.create();
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
return true;
}
}).build();
b.setSSLContext(sslContext);
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslSocketFactory)
.build();
PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
b.setConnectionManager(connMgr);
HttpClient client = b.build();
HttpPost post = new HttpPost(myurl);
List<NameValuePair> params = new ArrayList<NameValuePair>(args.length);
params.add(new BasicNameValuePair("hash", hash));
for(int i = 0; i < args.length; i++) {
params.add(new BasicNameValuePair("arg"+i, args[i]));
}
post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream in = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
System.out.println("[POSTRequest] Data sent successfully!");
while ((line = reader.readLine()) != null) {
System.out.println("[POSTRequest] Report: "+line);
}
}
}
}
EDIT: I'm using Ant to build, and the dependencies are correctly added. I tested too with Maven, adding the dependencies, but the error remains.
EDIT2: Switched to Maven, added maven-shade-plugin and maven-compile-plugin. The error disappeared, but now got this java.lang.NoSuchMethodError: org.apache.http.impl.client.HttpClientBuilder.setSSLContext. When running with junit, don't occurs any errors. It only occurs when running on server, that is Spigot 1.11.2 Minecraft Server.
if you are using a maven project, add the below dependency in your pom.xml file.
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
So, I replaced the sslcontext methods from apache httpclient and httpcore with javax sslcontext methods. Now, everything works fine. Remembering, that the above code was working normally on pure java. The real problem was when running on Minecraft server.
Anyway, i will put below the new code, for documentation, maybe helps someone.
package com.b5team.postrequest;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class HttpsPOSTRequest {
public static void sendRequest(String myurl, String hash, String args[]) throws NoSuchAlgorithmException, KeyManagementException {
try {
SSLContext context = SSLContext.getInstance("TLS");
context.init(new KeyManager[0], new TrustManager[] {new DefaultTrustManager()}, new SecureRandom());
SSLContext.setDefault(context);
URL url = new URL(myurl);
HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
con.setHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0;Windows98;DigExt)");
con.setDoOutput(true);
con.setDoInput(true);
ArrayList<String> params = new ArrayList<String>(args.length + 1);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes("hash=" + hash);
for(int i = 0; i < params.size(); i++) {
output.writeBytes("&");
output.writeBytes("arg" + i + "=" + args[i]);
output.flush();
}
output.flush();
output.close();
DataInputStream input = new DataInputStream(con.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line;
System.out.println("[POSTRequest] Data sent successfully!");
System.out.println("[POSTRequest] Resp Code:"+con.getResponseCode());
System.out.println("[POSTRequest] Resp Message:"+con.getResponseMessage());
while ((line = reader.readLine()) != null) {
System.out.println("[POSTRequest] Report: "+line);
}
input.close();
} catch (UnsupportedEncodingException e) {
System.out.println("[POSTRequest] Encoding error. Maybe string have invalid caracters.");
e.printStackTrace();
} catch (MalformedURLException e) {
System.out.println("[POSTRequest] Invalid URL. Verify your URL and try again.");
e.printStackTrace();
} catch (IOException e) {
System.out.println("[POSTRequest] Error on HTTPS connection.");
e.printStackTrace();
}
}
private static class DefaultTrustManager implements X509TrustManager {
#Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
#Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
#Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
}

Fetch Appdynamics data in Java

I want to execute the below command through Java code. This is to create connection to my Appdynamics Contoller
curl --user user#customer1:password 'http://192.168.1.11:9090/controller/rest/applications?output=JSON'
The java code that I have written for this is
import java.io.IOException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class Test {
private static HttpClient client;
public static void main(String[] args) {
CloseableHttpResponse response = null;
CloseableHttpClient httpclient = null;
try {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope("192.168.1.11", 9090), new UsernamePasswordCredentials(
"user", "password"));
httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
HttpPost httpget = new HttpPost("http://192.168.1.11:9090/controller/rest/applications?output=JSON");
System.out.println("Executing request " + httpget.getRequestLine());
response = httpclient.execute(httpget);
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
httpclient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
I keep on getting below error
HTTP/1.1 401 Unauthorized
Error report HTTP Status 401 - type Status reportmessagedescriptionThis request requires HTTP authentication ().
Can anyone please help.

javax.net.ssl.SSLException: Read error: ssl=0x56e63588: I/O error during system call, Connection reset by peer

I have been using using org.apache.http.client.HttpClient to download some data from a HTTP server for past 2 years and its been working fine.
Recently we switched to HTTPS for some security reasons.This is also working fine with WiFi and High speed mobile data(3G).But most often with slow data connection(2G) My download interrupted with following stack trace.
javax.net.ssl.SSLException: Read error: ssl=0x56e63588: I/O error during system call, Connection reset by peer
at com.android.org.conscrypt.NativeCrypto.SSL_read(Native Method)
at com.android.org.conscrypt.OpenSSLSocketImpl$SSLInputStream.read(OpenSSLSocketImpl.java:690)
at org.apache.http.impl.io.AbstractSessionInputBuffer.fillBuffer(AbstractSessionInputBuffer.java:103)
at org.apache.http.impl.io.AbstractSessionInputBuffer.read(AbstractSessionInputBuffer.java:120)
at org.apache.http.impl.io.ChunkedInputStream.read(ChunkedInputStream.java:131)
at org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:140)
at java.io.FilterInputStream.read(FilterInputStream.java:114)
This is how my Code Looks like :
HttpPost httpPost = new HttpPost(url);
UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(
params, HTTP.UTF_8);
httpPost.setEntity(p_entity);
response = httpClient.execute(httpPost);
DataInputStream in = new DataInputStream(response.getEntity().getContent());
String st = "";
result = new Vector<String>();
while ((st = readLine(in)) != null) {
result.addElement(st);
}
Try this:
package com.telpoo.frame.net;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
public class MySSLSocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS");
public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(truststore);
TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sslContext.init(null, new TrustManager[] { tm }, null);
}
#Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
}
#Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
public static HttpClient getNewHttpClient() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}
}
and use it:
URL myUrl = new URL(url);
HttpClient client = MySSLSocketFactory.getNewHttpClient(); // myHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), connectTimeout);
HttpPost post = new HttpPost(myUrl.toURI());

Categories

Resources