Https post works on android emulator but doesn't work on device

I am trying to send data to Https url using the below code. I checked the emulator it works fine. But it doesn't work on the device. Can someone please help me.

  public Boolean PostData(String data) throws IOException {
  Boolean response = false;
  TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
    public[] getAcceptedIssuers() {
      return null;

    public void checkClientTrusted([] certs, String authType) {

    public void checkServerTrusted([] certs, String authType) {

  // Install the all-trusting trust manager
  try {
    SSLContext sc = SSLContext.getInstance("TLS");
    sc.init(null, trustAllCerts, new;

  } catch (Exception e) {

  HostnameVerifier hostnameVerifier =

  SchemeRegistry registry = new SchemeRegistry();
  SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
  socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
  registry.register(new Scheme("https", socketFactory, 443));

  // Set verifier
  StringBuilder postDataBuilder = new StringBuilder();
  byte[] postData = postDataBuilder.toString().getBytes("UTF-8");

  URL postURL = new URL(url);

  HttpsURLConnection conn = (HttpsURLConnection) postURL.openConnection();
  HttpsURLConnection.setDefaultHostnameVerifier(new CustomizedHostnameVerifier());
  conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  conn.setRequestProperty("Content-Length", Integer.toString(postData.length));

  // ------------------
  OutputStream out = conn.getOutputStream();
  // --------------------------

  return response;

private static class CustomizedHostnameVerifier implements HostnameVerifier {
  public boolean verify(String hostname, SSLSession session) {
    return true;


Is there a way to get the response displayed on this URL after we post the data.

Thanks, Mahesh


source to share

1 answer

Have you used INTERNET permission?

You have to add to your manifest file:

<uses-permission android:name="android.permission.INTERNET" /> 


(The internet works fine with the emulator, but if you want to use it on a real device, you must use it)



All Articles