Saturday, December 1, 2012

Https Url parsing Data

public static String[] getSongData(String url) {
        String[] mTitle = new String[2];
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(OpenHttpsConnection(url));
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getElementsByTagName("NowPlaying");
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                Element fstElmnt = (Element) node;
                NodeList nameList = fstElmnt.getElementsByTagName("Title");
                Element nameElement = (Element) nameList.item(0);
                nameList = nameElement.getChildNodes();
                mTitle[0] = ((Node) nameList.item(0)).getNodeValue();
                NodeList websiteList = fstElmnt.getElementsByTagName("Artist");
                Element websiteElement = (Element) websiteList.item(0);
                websiteList = websiteElement.getChildNodes();
                mTitle[1] = ((Node) websiteList.item(0)).getNodeValue();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return mTitle;
    }

    public static InputStream OpenHttpsConnection(String strURL)
            throws IOException, NoSuchAlgorithmException,
            KeyManagementException {
        InputStream inputStream = null;
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, new X509TrustManager[] { new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain,
                    String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain,
                    String authType) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        } }, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(context
                .getSocketFactory());

        URL url = new URL(strURL);
        URLConnection conn = url.openConnection();
        try {
            HttpsURLConnection httpConn = (HttpsURLConnection) conn;
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            if (httpConn.getResponseCode() == HttpsURLConnection.HTTP_OK) {
                inputStream = httpConn.getInputStream();
            }
        } catch (Exception ex) {
        }
        return inputStream;
    }

Send Data to Server throught JSON in Android

HttpRequest class :

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.util.Log;

public class HttpRequest {

    DefaultHttpClient httpClient;
    HttpContext localContext;
    private String ret;

    HttpResponse response = null;
    HttpPost httpPost = null;
    HttpGet httpGet = null;

    public HttpRequest() {
       
        HttpParams myParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(myParams, 10000);
        HttpConnectionParams.setSoTimeout(myParams, 10000);
        httpClient = new DefaultHttpClient(myParams);
        localContext = new BasicHttpContext();
    }

    public void clearCookies() {
        httpClient.getCookieStore().clear();
    }

    public void abort() {
        try {
            if (httpClient != null) {
                System.out.println("Abort.");
                httpPost.abort();
            }
        } catch (Exception e) {
            System.out.println("abort" + e);
        }
    }

    public String sendPost(String url, String data) {
        return sendPost(url, data, null);
    }

    public String sendJSONPost(String url, JSONObject data) {
        return sendPost(url, data.toString(), "application/json");
    }

    public String sendPost(String url, String data, String contentType) {
        ret = null;

        httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY,
                CookiePolicy.RFC_2109);

        httpPost = new HttpPost(url);
        response = null;

        StringEntity tmp = null;

        httpPost.setHeader("User-Agent", "SET YOUR USER AGENT STRING HERE");
        httpPost
                .setHeader(
                        "Accept",
                        "text/html,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");

        if (contentType != null) {
            httpPost.setHeader("Content-Type", contentType);
        } else {
            httpPost.setHeader("Content-Type",
                    "application/x-www-form-urlencoded");
        }

        try {
            tmp = new StringEntity(data, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            System.out.println("Encode Exception" + e);
        }

        httpPost.setEntity(tmp);

        try {
            response = httpClient.execute(httpPost, localContext);

            if (response != null) {
                ret = EntityUtils.toString(response.getEntity());
            }
        } catch (Exception e) {
            System.out.println("Error in sendPost" + e);
        }

        return ret;
    }

    public String sendGet(String url) {
        httpGet = new HttpGet(url);

        try {
            response = httpClient.execute(httpGet);
        } catch (Exception e) {
            Log.e("Your App Name Here", e.getMessage());
        }

        try {
            ret = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            Log.e("Your App Name Here", e.getMessage());
        }

        return ret;
    }
}


JSON Data :

public JSONObject setJsonEmailMobile(Context c, String email, String mobile) {

        JSONObject jsData = new JSONObject();
        try {

            jsData.put("email", email);
            jsData.put("phone", mobile);
            Log.e("Json Data", "Json Data For Home is  : " + jsData.toString());

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return jsData;
    }

 Main Activity:

public void httpRequestSend() {

        try {
            HttpRequest http = new HttpRequest();
            response = http.sendJSONPost(url, setJsonEmailMobile(this,
                    edtEmail.getText().toString(), edtMobile.getText()
                            .toString()));

        } catch (Exception e) {
            response = "";
        }

    }