httpclient 활용 데이터 전송

|

http://mainia.tistory.com/568



org.apache.http.client.HttpClient 클래스는 안드로이드 뿐만 아니라 여러가지로

쓸만한데가 많아서 몇가지 예제를 정리 하였다나 같은 경우에는 안드로이드에서

서버와 통신하며 데이터를 받아올 때 사용한다안드로이드 API 내부에 HttpCliet

가 포함되어있기 때문이다.

 

(1) HttpClient 를 이용하여 POST 방식으로 멀티파일 업로드 구현

 

이 예제는 java application 으로 만든것이다서버에 WAS 가 돌고 있다면 멀티 파일 업로드가

가능하다로컬상에 web application 하나 구현해 놓고 테스트 해보면 될것이다.


01 import java.io.File;
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;
13  
14  
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);
19  
20     HttpPost httppost = new HttpPost("http://localhost:9001/upload.do");
21     File file = new File("c:/TRASH/zaba_1.jpg");
22  
23     MultipartEntity mpEntity = new MultipartEntity();
24     ContentBody cbFile = new FileBody(file, "image/jpeg");
25     mpEntity.addPart("userfile", cbFile);
26  
27  
28     httppost.setEntity(mpEntity);
29     System.out.println("executing request " + httppost.getRequestLine());
30     HttpResponse response = httpclient.execute(httppost);
31     HttpEntity resEntity = response.getEntity();
32  
33     System.out.println(response.getStatusLine());
34     if (resEntity != null) {
35       System.out.println(EntityUtils.toString(resEntity));
36     }
37     if (resEntity != null) {
38       resEntity.consumeContent();
39     }
40  
41     httpclient.getConnectionManager().shutdown();
42   }
43 }

 

(2) HttpClient  를 이용하여 일반 데이터 전송받기

 

이 예제는 파일이 아닌 일반 text 데이터를 BasicNameValuePair 담아서 전송한다하나하나 담은

데이터는 다시 ArrayList 클래스에 넣고 UrlEncodedFormEntity 클래스로 UTF-8 로 인코딩한다.

서버에서 작업된 내용을 받을때는 ISO-8859-1 디코더해서 BufferedReader 로 읽어 들인다

그리고 마지막에 getConnectionManager().shutdown() ; 해준다.

01 InputStream is = null;
02 String totalMessage = "";
04 HttpClient httpclient = new DefaultHttpClient();
05 try {
06     /** 연결 타입아웃내에 연결되는지 테스트, 5초 이내에 되지 않는다면 에러 */
07     String id = "id";
08     String pwd = "password";
09      
10     ArrayList<namevaluepair> nameValuePairs = new ArrayList<namevaluepair>();
11     nameValuePairs.add(new BasicNameValuePair("ID", id));
12     nameValuePairs.add(new BasicNameValuePair("PWD", pwd));
13          
14     /** 네트웍 연결해서 데이타 받아오기 */
15     String result = "";
16     HttpParams params = httpclient.getParams();
17     HttpConnectionParams.setConnectionTimeout(params, 5000);
18     HttpConnectionParams.setSoTimeout(params, 5000);
19  
20     HttpPost httppost = new HttpPost(url);
21     UrlEncodedFormEntity entityRequest =
22 new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
23     httppost.setEntity(entityRequest);
24          
25     HttpResponse response = httpclient.execute(httppost);
26     HttpEntity entityResponse = response.getEntity();
27     is = entityResponse.getContent();
28      
29     /** convert response to string */
30     BufferedReader reader = new BufferedReader(new InputStreamReader(
31             is, "iso-8859-1"), 8);
32     StringBuilder sb = new StringBuilder();
33     String line = null;
34     while ((line = reader.readLine()) != null) {
35         sb.append(line).append("\n");
36     }
37     is.close();
38     result = sb.toString();
39          
40 catch (IOException e) {
41     e.printStackTrace();
42 } chatch (Exception e)
43     e.printStackTrace();
44  
45 finally {
46     httpclient.getConnectionManager().shutdown();
47 }
48 </namevaluepair></namevaluepair>

 

위의 내용은 아이디/패스를 서버에 전달하고 그 결과값을 받기 위해서 만들었던 것이다.

서버나 네트웍 상태가 안좋아서 데이터를 받아 올수 없을 때 무작정 기다릴수 없으므로

5초로 셋팅해주었다. 5초 이상 반응이 없으면 exception 을 던지게 된다.

 

이것으로 안드로이드에서 실시간 서비스정보구현을 위한 기본적인 코딩은 된것이다.

추가로 구현해야될 사항은 네트웍 연결부분을 별도의 쓰레드로 돌려야 되고 , 데이터를

받고 전달해줄 서버를 구현해야한다그리고 JSON 프로토콜을 사용할것이 때문에

JSON 파싱을 위한 구현을 해야한다.


'Android 개발 > Android SDK' 카테고리의 다른 글

안드로이드 2.0 이상 주소록 삽입  (0) 2011.04.19
Android Mime Type  (0) 2011.04.14
안드로이드 문서 링크 모음 !!!!!!!!!!!!!!!!!!!!!!!!!  (0) 2011.04.13
Avoiding Memory Leaks  (0) 2011.04.13
Start Service at boot  (0) 2011.04.13
And