------

[ AD ] Port Monitor ( Try to use a Best WebSite Monitoring Tool )

------

안드로이드 플랫폼에서 http 리소스에 접근하는 여러가지 방법

첫번째 :  HttpURLConnection  ( java.net )
( get input  stream / given simple url )

1) basic
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;
 
	}

2) post method
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;
}


두번째 : HttpClinet
( get input stream / given simple url )
1) 더 쉽고 나은 방법!
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;
}

2) post method
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;
	        }
}

3) reading sending a cookie
retrieve cookies
[...]
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;
				}
			}
}
send a cookie ( w/ request )
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));

'0.일반개발' 카테고리의 다른 글

갤럭시S 프로요 업그레이드  (0) 2010.09.17
HTTP 연결 테스트 모듈 만들기  (0) 2010.09.16
애플 에어 프린트 ^^ 와우~~~  (0) 2010.09.16
SQLite3  (0) 2010.09.16
XML 파싱 Parsing Parser 파서  (0) 2010.09.16

+ Recent posts