자료출처 : http://mainia.tistory.com/568
개발환경 : JDK 1.5, eclipse-galileo, Google API 7(android API 2.1), window XP |
org.apache.http.client.HttpClient 클래스는 안드로이드 뿐만 아니라 여러가지로
쓸만한데가 많아서 몇가지 예제를 정리 하였다. 나 같은 경우에는 안드로이드에서
서버와 통신하며 데이터를 받아올 때 사용한다. 안드로이드 API 내부에 HttpCliet
가 포함되어있기 때문이다.
(1) HttpClient 를 이용하여 POST 방식으로 멀티파일 업로드 구현 |
이 예제는 java application 으로 만든것이다. 서버에 WAS 가 돌고 있다면 멀티 파일 업로드가
가능하다. 로컬상에 web application 하나 구현해 놓고 테스트 해보면 될것이다.
02 | import org.apache.http.HttpEntity; |
03 | import org.apache.http.HttpResponse; |
04 | import org.apache.http.HttpVersion; |
05 | import org.apache.http.client.HttpClient; |
06 | import org.apache.http.client.methods.HttpPost; |
07 | import org.apache.http.entity.mime.MultipartEntity; |
08 | import org.apache.http.entity.mime.content.ContentBody; |
09 | import org.apache.http.entity.mime.content.FileBody; |
10 | import org.apache.http.impl.client.DefaultHttpClient; |
11 | import org.apache.http.params.CoreProtocolPNames; |
12 | import org.apache.http.util.EntityUtils; |
15 | public class PostFile { |
16 | public static void main(String[] args) throws Exception { |
17 | HttpClient httpclient = new DefaultHttpClient(); |
18 | httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); |
21 | File file = new File( "c:/TRASH/zaba_1.jpg" ); |
23 | MultipartEntity mpEntity = new MultipartEntity(); |
24 | ContentBody cbFile = new FileBody(file, "image/jpeg" ); |
25 | mpEntity.addPart( "userfile" , cbFile); |
28 | httppost.setEntity(mpEntity); |
29 | System.out.println( "executing request " + httppost.getRequestLine()); |
30 | HttpResponse response = httpclient.execute(httppost); |
31 | HttpEntity resEntity = response.getEntity(); |
33 | System.out.println(response.getStatusLine()); |
34 | if (resEntity != null ) { |
35 | System.out.println(EntityUtils.toString(resEntity)); |
37 | if (resEntity != null ) { |
38 | resEntity.consumeContent(); |
41 | httpclient.getConnectionManager().shutdown(); |
(2) HttpClient 를 이용하여 일반 데이터 전송/ 받기 |
이 예제는 파일이 아닌 일반 text 데이터를 BasicNameValuePair 담아서 전송한다. 하나하나 담은
데이터는 다시 ArrayList 클래스에 넣고 UrlEncodedFormEntity 클래스로 UTF-8 로 인코딩한다.
서버에서 작업된 내용을 받을때는 ISO-8859-1 디코더해서 BufferedReader 로 읽어 들인다
그리고 마지막에 getConnectionManager().shutdown() ; 해준다.
02 | String totalMessage = "" ; |
04 | HttpClient httpclient = new DefaultHttpClient(); |
06 | /** 연결 타입아웃내에 연결되는지 테스트, 5초 이내에 되지 않는다면 에러 */ |
08 | String pwd = "password" ; |
10 | ArrayList<namevaluepair> nameValuePairs = new ArrayList<namevaluepair>(); |
11 | nameValuePairs.add( new BasicNameValuePair( "ID" , id)); |
12 | nameValuePairs.add( new BasicNameValuePair( "PWD" , pwd)); |
14 | /** 네트웍 연결해서 데이타 받아오기 */ |
16 | HttpParams params = httpclient.getParams(); |
17 | HttpConnectionParams.setConnectionTimeout(params, 5000 ); |
18 | HttpConnectionParams.setSoTimeout(params, 5000 ); |
20 | HttpPost httppost = new HttpPost(url); |
21 | UrlEncodedFormEntity entityRequest = |
22 | new UrlEncodedFormEntity(nameValuePairs, "UTF-8" ); |
23 | httppost.setEntity(entityRequest); |
25 | HttpResponse response = httpclient.execute(httppost); |
26 | HttpEntity entityResponse = response.getEntity(); |
27 | is = entityResponse.getContent(); |
29 | /** convert response to string */ |
30 | BufferedReader reader = new BufferedReader( new InputStreamReader( |
31 | is, "iso-8859-1" ), 8 ); |
32 | StringBuilder sb = new StringBuilder(); |
34 | while ((line = reader.readLine()) != null ) { |
35 | sb.append(line).append( "\n" ); |
38 | result = sb.toString(); |
40 | } catch (IOException e) { |
46 | httpclient.getConnectionManager().shutdown(); |
48 | </namevaluepair></namevaluepair> |
위의 내용은 아이디/패스를 서버에 전달하고 그 결과값을 받기 위해서 만들었던 것이다.
서버나 네트웍 상태가 안좋아서 데이터를 받아 올수 없을 때 무작정 기다릴수 없으므로
5초로 셋팅해주었다. 5초 이상 반응이 없으면 exception 을 던지게 된다.
이것으로 안드로이드에서 실시간 서비스정보구현을 위한 기본적인 코딩은 된것이다.
추가로 구현해야될 사항은 네트웍 연결부분을 별도의 쓰레드로 돌려야 되고 , 데이터를
받고 전달해줄 서버를 구현해야한다. 그리고 JSON 프로토콜을 사용할것이 때문에
JSON 파싱을 위한 구현을 해야한다.