`
tracyhuyan
  • 浏览: 82681 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

Different ways to access HTTP resources from Android(cf)

阅读更多
from:  http://blog.dahanne.net/2009/08/16/how-to-access-http-resources-from-android/

First Method : getting an input stream given a simple url from Android using HttpURLConnection

This method is the most basic one : it allows you, using the basic HttpUrlConnection, ( contained in java.net) to get an InputStream from an Url :

 

private InputStream downloadUrl(String url) {
		HttpURLConnection con = null;
		URL url;
		InputStream is=null;
		try {
			url = new URL(url);
			con = (HttpURLConnection) url.openConnection();
			con.setReadTimeout(10000 /* milliseconds */);
			con.setConnectTimeout(15000 /* milliseconds */);
			con.setRequestMethod("GET");
			con.setDoInput(true);
			con.addRequestProperty("Referer", "http://blog.dahanne.net");
			// Start the query
			con.connect();
			is = con.getInputStream();
		}catch (IOException e) {
                        //handle the exception !
			e.printStackTrace();
		}
		return is;
 
	}
 

You can also use the Post method, sending data in the HTTP POST payload :

 

private InputStream downloadUrl(String url) {
                InputStream myInputStream =null;
		StringBuilder sb = new StringBuilder();
                //adding some data to send along with the request to the server
		sb.append("name=Anthony");
		URL url;
		try {
			url = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			conn.setRequestMethod("POST");
			OutputStreamWriter wr = new OutputStreamWriter(conn
					.getOutputStream());
                        // this is were we're adding post data to the request
                        wr.write(sb.toString());
			wr.flush();
			myInputStream = conn.getInputStream();
			wr.close();
		} catch (Exception e) {
                        //handle the exception !
			Log.d(TAG,e.getMessage());
		}
                return myInputStream;
}

 

But there are better ways to achieve that, using Apache HttpClient, included in android.jar (no need to add another jar, it’s included in android core)

Second Method : getting an input stream given a simple url from Android using HttpClient

Why is it a better to do it ? because the simpler, the better ! See by yourself :

 

public static InputStream getInputStreamFromUrl(String url) {
		InputStream content = null;
		try {
			HttpGet httpGet = new HttpGet(url);
			HttpClient httpclient = new DefaultHttpClient();
			// Execute HTTP Get Request
			HttpResponse response = httpclient.execute(httpGet);
			content = response.getEntity().getContent();
                } catch (Exception e) {
			//handle the exception !
		}
		return content;
}

 

But you maybe wondering if it’s still easy with HTTP Post method ? You won’t be deceived !

 

 

public static InputStream getInputStreamFromUrl(String url) {
		InputStream content = null;
		try {
          		HttpClient httpclient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);
			List nameValuePairs = new ArrayList(1);
                        //this is where you add your data to the post method
                        nameValuePairs.add(new BasicNameValuePair(
			"name", "anthony"));
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			// Execute HTTP Post Request
			HttpResponse response = httpclient.execute(httpPost);
			content = response.getEntity().getContent();
		        return content;
	        }
}

 But what if you want to read a cookie from the response ? And how can you send a cookie back to the server for the next request ?

 

Reading / Sending a cookie along with the requests

 

Using Apache HttpClient, it’s easy to retrieve cookies ! Everything is in the headers after all !

 

[...]
Cookie sessionCookie =null;
HttpResponse response = httpclient.execute(httpPost);
Header[] allHeaders = response.getAllHeaders();
CookieOrigin origin = new CookieOrigin(host, port,path, false);
for (Header header : allHeaders) {
			List parse = cookieSpecBase.parse(header, origin);
			for (Cookie cookie : parse) {
				// THE cookie
				if (cookie.getName().equals(COOKIE_I_WAS_LOOKING_FOR)
						&& cookie.getValue() != null && cookie.getValue() != "") {
					sessionCookie = cookie;
				}
			}
}

 

 To send a cookie along with your request, keep it simple :

 

HttpPost httpPost = new HttpPost(url);
CookieSpecBase cookieSpecBase = new BrowserCompatSpec();
List cookies = new ArrayList();
cookies.add(sessionCookie);
List cookieHeader = cookieSpecBase.formatCookies(cookies);
// Setting the cookie
httpPost.setHeader(cookieHeader.get(0));

 What about the resulting InputStream ? You definitely want to transform it into a String or an Drawable (to set it to an ImageView for example !) don’t you ?

Converting the InputStream into a Drawable in Android

The Drawable class already handles that for you :

 

Drawable d = Drawable.createFromStream(myInputStream, "nameOfMyResource");

 

Converting the InputStream into a String in Android

This is some classic java stuff (don’t tell about how easier it is in Ruby.. I know :-( … but hey ! Java SE7 at the rescue with NIO !!! maybe one day in 2010 ! )

 

BufferedReader rd = new BufferedReader(new InputStreamReader(myInputStreamToReadIntoAString), 4096);
String line;
StringBuilder sb =  new StringBuilder();
while ((line = rd.readLine()) != null) {
		sb.append(line);
}
rd.close();
String contentOfMyInputStream = sb.toString()
 
That's it folks ! If you have any other methods to achieve these goals, feel free to share them sending a comment !
 

 

分享到:
评论

相关推荐

    java-leetcode题解之Different Ways to Add Parentheses.java

    java java_leetcode题解之Different Ways to Add Parentheses.java

    android sdk 自带 实例(samples)

    A simple example that illustrates a few different ways for an application to implement support for the Android data backup and restore mechanism. Bluetooth Chat An application for two-way text ...

    Four different tricks to bypass StackShield and StackGuard protection

    Four different tricks to bypass StackShield and StackGuard protection Four different tricks to bypass StackShield and StackGuard protection Four different tricks to bypass StackShield and StackGuard ...

    Exploring SE for Android 无水印书签修正版pdf

    Discover how to leverage SE for Android to secure your own projects in powerful ways using this step by step guide. Who This Book Is For This book is intended for developers and engineers with some ...

    cisco_ios_access_lists.pdf

    access lists that control access to router resources and to hosts, and discusses the tradeoffs of different kinds of access lists. The chapter includes explanations of how certain protocols work and...

    Scrum.and.Xp.from.the.Trenches.2nd.Edition.1329224272

    This book aims to give you a ... They also experimented with XP practices - different ways of doing continuous build, pair programming, test driven development, etc, and how to combine this with Scrum.

    CommonsWare.The.Busy.Coders.Guide.to.Android.Development.Version.8.2.2017

    Android, the next-generation open mobile platform from Google and the Open Handset Alliance, is poised to become a significant player in the mobile device market. The Android platform gives developers...

    Android代码-Android-Bluetooth-Simulator

    What you need to do in order to use the simulator instead of the android API, is to change the import from android.bluetooth to dk.itu.android.bluetooth (and also add the INTERNET permission in the ...

    Gradle for Android

    What You Will Learn, Build new Android apps and libraries using Android Studio and Gradle, Migrate projects from Eclipse to Android Studio and Gradle, Manage the local and remote dependencies of your...

    Pro Entity Framework Core 2 for ASP.NET Core MVC

    He begins by describing the different ways that Entity Framework Core 2 can model data and the different types of databases that can be used. He then shows you how to use Entity Framework Core 2 in ...

    Android Studio Essentials

    This guide aims to provide a comprehensive overview of the essential aspects of Android Studio, covering everything from its setup and basic functionalities to advanced features that can ...

    大学英语综合教程Ways of Learning

    Howard Gardner, a professor of education at Harvard University, reflects on a visit to China and gives his thoughts on different approaches to learning in China and the West. LEARNING, CHINESE-STYLE ...

    Extreme Linux Performance Monitoring Part II

    介绍linux io 监控和优化,文字简单到位。 Disk IO subsystems are the slowest part of any ... The following subsections describe the different ways the kernel processes data IO from disk to memory and back.

Global site tag (gtag.js) - Google Analytics