Android Tutorial - Network
- Cookie
- Restful
- Socket
- SSL
- RSS
- NetworkInfo
- ConnectivityManager
Cookie Cache
/** * */ //package org.alldroid.forum.net; import java.util.List; import org.apache.http.client.CookieStore; import org.apache.http.cookie.Cookie; import org.apache.http.impl.client.BasicCookieStore; /** * @author trr4rac * */ public class CookieCache { private CookieStore store; private LoginCookie cookie; private CookieCache ( ) { setCookieStore ( new BasicCookieStore () ); } public String get ( String name ) { List<Cookie> cookies = this.getCookieStore ().getCookies (); for ( int i = 0; i < cookies.size (); i++ ) { Cookie c = cookies.get ( i ); if ( c.getName ().equals ( name ) ) { return c.getValue (); } } return null; } /** * @param store the store to set */ private void setCookieStore ( CookieStore store ) { this.store = store; } /** * @return the store */ public CookieStore getCookieStore ( ) { return store; } private static CookieCache instance; public static CookieCache getInstance ( ) { if ( instance == null ) { instance = new CookieCache (); } return instance; } /** * @param cookie the cookie to set */ public void setCookie ( LoginCookie cookie ) { this.cookie = cookie; } /** * @return the cookie */ public LoginCookie getCookie ( ) { return cookie; } } class LoginCookie { private String sessionHash; private long lastAvctivity; private long lastVisit; private String passwordHash; private String userId; /** * @param sessionHash the sessionHash to set */ public void setSessionHash ( String sessionHash ) { this.sessionHash = sessionHash; } /** * @return the sessionHash */ public String getSessionHash ( ) { return sessionHash; } /** * @param lastAvctivity the lastAvctivity to set */ public void setLastAvctivity ( long lastAvctivity ) { this.lastAvctivity = lastAvctivity; } /** * @return the lastAvctivity */ public long getLastAvctivity ( ) { return lastAvctivity; } /** * @param lastVisit the lastVisit to set */ public void setLastVisit ( long lastVisit ) { this.lastVisit = lastVisit; } /** * @return the lastVisit */ public long getLastVisit ( ) { return lastVisit; } /** * @param passwordHash the passwordHash to set */ public void setPasswordHash ( String passwordHash ) { this.passwordHash = passwordHash; } /** * @return the passwordHash */ public String getPasswordHash ( ) { return passwordHash; } /** * @param userId the userId to set */ public void setUserId ( String userId ) { this.userId = userId; } /** * @return the userId */ public String getUserId ( ) { return userId; } }
Restful authentication task
package app.test; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.AbstractHttpClient; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; public class RestAuthTask extends AsyncTask<HttpUriRequest, Void, String> { public static final String HTTP_RESPONSE = "httpResponse"; private static final String AUTH_USER = "user@mydomain.com"; private static final String AUTH_PASS = "password"; private Context mContext; private AbstractHttpClient mClient; private String mAction; public RestAuthTask(Context context, String action, boolean authenticate) { mContext = context; mAction = action; mClient = new DefaultHttpClient(); if(authenticate) { UsernamePasswordCredentials creds = new UsernamePasswordCredentials(AUTH_USER, AUTH_PASS); mClient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds); } } public RestAuthTask(Context context, String action, AbstractHttpClient client) { mContext = context; mAction = action; mClient = client; } @Override protected String doInBackground(HttpUriRequest... params) { try{ HttpUriRequest request = params[0]; HttpResponse serverResponse = mClient.execute(request); BasicResponseHandler handler = new BasicResponseHandler(); String response = handler.handleResponse(serverResponse); return response; } catch (Exception e) { e.printStackTrace(); return null; } } @Override protected void onPostExecute(String result) { Intent intent = new Intent(mAction); intent.putExtra(HTTP_RESPONSE, result); mContext.sendBroadcast(intent); } }
Restful Client
//package com.herochen.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; class RestClient { private static final String TAG = "CareClient-RestClient"; public static final String server = "http://174.140.165.237"; //public static final String server = "http://192.168.1.101:8080"; private static String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } public static JSONObject get(String url, Map<String,String> params){ HttpClient httpClient = new DefaultHttpClient(); // Prepare a request object if(params != null){ int i = 0; for(Map.Entry<String, String> param : params.entrySet()){ if(i == 0){ url += "?"; } else { url += "&"; } try { url += param.getKey()+"="+URLEncoder.encode(param.getValue(),"UTF-8"); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.getMessage()); } i++; } } HttpGet httpGet = new HttpGet(url); // Execute the request HttpResponse response = null; JSONObject json = null; try { //???????????GET??????????????????? response = httpClient.execute(httpGet); Log.i("GET status code:",response.getStatusLine().toString()); // Get hold of the response entity HttpEntity entityResp = response.getEntity(); if (entityResp != null) { // A Simple JSON Response Read InputStream instream = entityResp.getContent(); String result = convertStreamToString(instream); // A Simple JSONObject Creation json = new JSONObject(result); // Closing the input stream will trigger connection release instream.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return json; } public static JSONObject post(String url, HttpEntity entityReq){ HttpClient httpClient = new DefaultHttpClient(); // Prepare a request object HttpPost httpPost = new HttpPost(url); // Execute the request HttpResponse response = null; JSONObject json = null; try { httpPost.setEntity(entityReq); //httpPost.setHeader(name, value); //???????????POST??????????????????? response = httpClient.execute(httpPost); Log.i("POST status code:",response.getStatusLine().toString()); // Get hold of the response entity HttpEntity entityResp = response.getEntity(); if (entityResp != null) { // A Simple JSON Response Read InputStream instream = entityResp.getContent(); String result = convertStreamToString(instream); // A Simple JSONObject Creation json = new JSONObject(result); // Closing the input stream will trigger connection release instream.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return json; } public static JSONObject put(String url, HttpEntity entityReq){ HttpClient httpClient = new DefaultHttpClient(); // Prepare a request object HttpPut httpPut = new HttpPut(url); // Execute the request HttpResponse response = null; JSONObject json = null; try { httpPut.setEntity(entityReq); //httpPost.setHeader(name, value); //???????????PUT??????????????????? response = httpClient.execute(httpPut); Log.i("PUT status code:",response.getStatusLine().toString()); // Get hold of the response entity HttpEntity entityResp = response.getEntity(); if (entityResp != null) { // A Simple JSON Response Read InputStream instream = entityResp.getContent(); String result = convertStreamToString(instream); // A Simple JSONObject Creation json = new JSONObject(result); // Closing the input stream will trigger connection release instream.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return json; } }
Rest Client
//package com.mediaportal.ampdroid.api.rest; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URLEncoder; import java.util.ArrayList; 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.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; public class RestClient { public enum RequestMethod { GET, POST } private ArrayList<NameValuePair> params; private ArrayList<NameValuePair> headers; private String contentBody; private String url; private int responseCode; private String message; private String response; public String getResponse() { return response; } public String getErrorMessage() { return message; } public int getResponseCode() { return responseCode; } public RestClient(String url) { this.url = url; params = new ArrayList<NameValuePair>(); headers = new ArrayList<NameValuePair>(); } public void AddParam(String name, String value) { params.add(new BasicNameValuePair(name, value)); } public void AddHeader(String name, String value) { headers.add(new BasicNameValuePair(name, value)); } public void Execute(RequestMethod method) throws Exception { switch (method) { case GET: { // add parameters String combinedParams = ""; if (!params.isEmpty()) { combinedParams += "?"; for (NameValuePair p : params) { String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(), "UTF-8"); if (combinedParams.length() > 1) { combinedParams += "&" + paramString; } else { combinedParams += paramString; } } } HttpGet request = new HttpGet(url + combinedParams); // add headers for (NameValuePair h : headers) { request.addHeader(h.getName(), h.getValue()); } executeRequest(request, url); break; } case POST: { HttpPost request = new HttpPost(url); // add headers for (NameValuePair h : headers) { request.addHeader(h.getName(), h.getValue()); } if (contentBody != null) { request.setEntity(new StringEntity(contentBody)); request.setHeader("Content-Type", "application/x-www-form-urlencoded"); } else if (!params.isEmpty()) { request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); } executeRequest(request, url); break; } } } private void executeRequest(HttpUriRequest request, String url) { HttpClient client = new DefaultHttpClient(); // client.getParams().s HttpResponse httpResponse; try { httpResponse = client.execute(request); responseCode = httpResponse.getStatusLine().getStatusCode(); message = httpResponse.getStatusLine().getReasonPhrase(); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); response = convertStreamToString(instream); // Closing the input stream will trigger connection release instream.close(); } } catch (ClientProtocolException e) { client.getConnectionManager().shutdown(); e.printStackTrace(); } catch (IOException e) { client.getConnectionManager().shutdown(); e.printStackTrace(); } } private static String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } public void setContentBody(String _body) { contentBody = _body; } }
Ping Server
import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; class Main { public static boolean pingGgServer(InetAddress addr, int port, int timeout) { Socket socket = new Socket(); Exception exception = null; try { socket.connect(new InetSocketAddress(addr, port), timeout); } catch (IOException e) { exception = e; } finally { try { socket.close(); } catch (IOException e) { } } return exception == null ? true : false; } }
Returns a SSL Factory instance that accepts all server certificates.
//package backend.snippets; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import android.util.Log; public class HttpsUtils { private static SSLSocketFactory sslSocketFactory; /** * Returns a SSL Factory instance that accepts all server certificates. * <pre>SSLSocket sock = * (SSLSocket) getSocketFactory.createSocket ( host, 443 ); </pre> * @return An SSL-specific socket factory. **/ public static final SSLSocketFactory getSocketFactory() { if ( sslSocketFactory == null ) { try { TrustManager[] tm = new TrustManager[] { new NaiveTrustManager() }; SSLContext context = SSLContext.getInstance ("TLSv1"); context.init( new KeyManager[0], tm, new SecureRandom( ) ); sslSocketFactory = (SSLSocketFactory) context.getSocketFactory (); } catch (KeyManagementException e) { Log.e ("No SSL algorithm support: " + e.getMessage(), e.toString()); } catch (NoSuchAlgorithmException e) { Log.e ("Exception when setting up the Naive key management.", e.toString()); } } return sslSocketFactory; } }
Fake Socket Factory
package org.acra.util; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.security.GeneralSecurityException; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.TrustManager; import org.apache.http.conn.scheme.LayeredSocketFactory; import org.apache.http.conn.scheme.SocketFactory; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.X509TrustManager; class NaiveTrustManager implements X509TrustManager { @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } @Override public void checkClientTrusted(X509Certificate[] x509CertificateArray, String string) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] x509CertificateArray, String string) throws CertificateException { } } public class FakeSocketFactory implements SocketFactory, LayeredSocketFactory { private SSLContext sslcontext = null; private static SSLContext createEasySSLContext() throws IOException { try { final SSLContext context = SSLContext.getInstance("TLS"); context.init(null, new TrustManager[] { new NaiveTrustManager() }, null); return context; } catch (GeneralSecurityException e) { throw new IOException(e); } } private SSLContext getSSLContext() throws IOException { if (this.sslcontext == null) { this.sslcontext = createEasySSLContext(); } return this.sslcontext; } @Override public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException { final int connTimeout = HttpConnectionParams.getConnectionTimeout(params); final int soTimeout = HttpConnectionParams.getSoTimeout(params); final InetSocketAddress remoteAddress = new InetSocketAddress(host, port); final SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket()); if ((localAddress != null) || (localPort > 0)) { // we need to bind explicitly if (localPort < 0) { localPort = 0; // indicates "any" } final InetSocketAddress isa = new InetSocketAddress(localAddress, localPort); sslsock.bind(isa); } sslsock.connect(remoteAddress, connTimeout); sslsock.setSoTimeout(soTimeout); return sslsock; } @Override public Socket createSocket() throws IOException { return getSSLContext().getSocketFactory().createSocket(); } @Override public boolean isSecure(Socket arg0) throws IllegalArgumentException { return true; } @Override public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException { return getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose); } }
Rss Parser
//package com.dreamcode.anfeedreader.utils; import java.io.InputStream; import java.net.URL; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; class FeedItem { private int feed_id; private int id; private String title; private String description; private String link; private String pubDate; private String md5hash; private String status; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getMd5hash() { return md5hash; } public void setMd5hash(String md5hash) { this.md5hash = md5hash; } public int getFeed_id() { return feed_id; } public void setFeed_id(int feed_id) { this.feed_id = feed_id; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getPubDate() { return pubDate; } public void setPubDate(String pubDate) { this.pubDate = pubDate; } public String toString() { return (this.title + ": " + this.pubDate + "n" + this.description); } } /* Usage: RssParser rp = new RssParser("<RSS Feed URL>"); rp.parse(); RssFeed feed = rp.getFeed(); // Listing all categories & the no. of elements in each category if (feed.getCategory() != null) { System.out.println("Category List: "); for (String category : feed.getCategory().keySet()) { System.out.println(category + ": " + ((ArrayList<FeedItem>)feed.getCategory().get(category)).size()); } } // Listing all items in the feed for (int i = 0; i < feed.getItems().size(); i++) System.out.println(feed.getItems().get(i).getTitle()); */ public class RssParser extends DefaultHandler { private String urlString; private RssFeed rssFeed; private StringBuilder text; private FeedItem item; public RssParser(String url) { this.urlString = url; this.text = new StringBuilder(); } public void parse() { InputStream urlInputStream = null; SAXParserFactory spf = null; SAXParser sp = null; try { URL url = new URL(this.urlString); urlInputStream = url.openConnection().getInputStream(); spf = SAXParserFactory.newInstance(); XMLReader reader = null; if (spf != null) { sp = spf.newSAXParser(); // sp.parse(urlInputStream, this); reader = sp.getXMLReader(); reader.setContentHandler(this); reader.parse(new InputSource(urlInputStream)); } } /* * Exceptions need to be handled * MalformedURLException * ParserConfigurationException * IOException * SAXException */ catch (Exception e) { System.out.println("Exception: " + e); e.printStackTrace(); } finally { try { if (urlInputStream != null) urlInputStream.close(); } catch (Exception e) {} } } public RssFeed getFeed() { return (this.rssFeed); } public void startElement(String uri, String localName, String qName, Attributes attributes) { if (localName.equalsIgnoreCase("channel")) this.rssFeed = new RssFeed(); else if (localName.equalsIgnoreCase("item") && (this.rssFeed != null)) { this.item = new FeedItem(); this.rssFeed.addItem(this.item); } } public void endElement(String uri, String localName, String qName) { if (this.rssFeed == null) return; if (localName.equalsIgnoreCase("item")) this.item = null; else if (localName.equalsIgnoreCase("title")) { if (this.item != null) this.item.setTitle(this.text.toString().trim()); else this.rssFeed.title = this.text.toString().trim(); } else if (localName.equalsIgnoreCase("link")) { if (this.item != null) this.item.setLink(this.text.toString().trim()); else this.rssFeed.link = this.text.toString().trim(); } else if (localName.equalsIgnoreCase("description")) { if (this.item != null) this.item.setDescription(this.text.toString().trim()); else this.rssFeed.description = this.text.toString().trim(); } else if (localName.equalsIgnoreCase("pubDate") && (this.item != null)) this.item.setPubDate(this.text.toString().trim()); this.text.setLength(0); } public void characters(char[] ch, int start, int length) { this.text.append(ch, start, length); } public static class RssFeed { public String title; public String description; public String link; private LinkedList <FeedItem> items; private HashMap <String, List <FeedItem>> category; public void addItem(FeedItem item) { if (this.items == null) this.items = new LinkedList<FeedItem>(); this.items.add(item); } public void addItem(String category, FeedItem item) { if (this.category == null) this.category = new HashMap<String, List<FeedItem>>(); if (!this.category.containsKey(category)) this.category.put(category, new LinkedList<FeedItem>()); this.category.get(category).add(item); } public List<FeedItem> getItems() { return items; } public void setItems(List<FeedItem> items) { this.items = (LinkedList<FeedItem>) items; } public HashMap<String, List<FeedItem>> getCategory() { return category; } public void setCategory(HashMap<String, List<FeedItem>> category) { this.category = category; } } }
NetworkInfo.State
import android.net.ConnectivityManager; import android.net.NetworkInfo; class Main { public static boolean checkInternet(Object systemService) { ConnectivityManager connect = (ConnectivityManager) systemService; if (connect.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED || connect.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED) { return true; } return false; } }
Network Information
//package com.varma.utils.netutils; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; public class NetInfo { private ConnectivityManager connManager = null; private WifiManager wifiManager = null; private WifiInfo wifiInfo = null; public NetInfo(Context context) { connManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE); wifiInfo = wifiManager.getConnectionInfo(); } public int getCurrentNetworkType() { if (null == connManager) return 0; NetworkInfo netinfo = connManager.getActiveNetworkInfo(); return netinfo.getType(); } public String getWifiIpAddress() { if (null == wifiManager || null == wifiInfo) return ""; int ipAddress = wifiInfo.getIpAddress(); return String.format("%d.%d.%d.%d", (ipAddress & 0xff), (ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff)); } public String getWiFiMACAddress() { if (null == wifiManager || null == wifiInfo) return ""; return wifiInfo.getMacAddress(); } public String getWiFiSSID() { if (null == wifiManager || null == wifiInfo) return ""; return wifiInfo.getSSID(); } public String getIPAddress() { String ipaddress = ""; try { Enumeration<NetworkInterface> enumnet = NetworkInterface.getNetworkInterfaces(); NetworkInterface netinterface = null; while(enumnet.hasMoreElements()) { netinterface = enumnet.nextElement(); for (Enumeration<InetAddress> enumip = netinterface.getInetAddresses(); enumip.hasMoreElements();) { InetAddress inetAddress = enumip.nextElement(); if(!inetAddress.isLoopbackAddress()) { ipaddress = inetAddress.getHostAddress(); break; } } } } catch (SocketException e) { e.printStackTrace(); } return ipaddress; } }
Using ConnectivityManager
import android.content.Context; import android.net.ConnectivityManager; class NetworkUtil { public static boolean CheckNetwork(Context context) { boolean flag = false; ConnectivityManager cwjManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); if (cwjManager.getActiveNetworkInfo() != null) flag = cwjManager.getActiveNetworkInfo().isAvailable(); return flag; } }