Tag Archives: 파일첨부

[Android] 안드로이드 플랫폼에서 HTTP GET/POST/Multipart POST 요청 처리하기

안드로이드 환경에서 HTTP 요청을 날리기 위해서 할 수 있는 방법으로는 여러가지가 있겠습니다만, POST에서 인코딩된 한글 문자열을 처리한다거나 파일을 첨부한다거나 하는 경우에는 아무래도 생각할것이 많아질 것 같습니다.

간단하게 도움이 될만한 예제를 발견하여 포스팅 해봅니다. 이 예제를 실행해 보기 위해서는 apache-mime4jhttpmime 라이브러리가 필요합니다.

HTTP GET

try
{
  HttpClient client = new DefaultHttpClient();  
  String getURL = "http://www.google.com";
  HttpGet get = new HttpGet(getURL);
  HttpResponse responseGet = client.execute(get);
  HttpEntity resEntityGet = responseGet.getEntity();
  if (resEntityGet != null) {
    // 결과를 처리합니다.
    Log.i("RESPONSE", EntityUtils.toString(resEntityGet));
  }
} catch (Exception e) { e.printStackTrace(); }

HTTP POST

try
{
  HttpClient client = new DefaultHttpClient();  
  String postURL = "http://www.google.com";
  HttpPost post = new HttpPost(postURL); 

  List<NameValuePair> params = new ArrayList<NameValuePair>();
  params.add(new BasicNameValuePair("user", "kris"));
  params.add(new BasicNameValuePair("pass", "xyz"));

  UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
  post.setEntity(ent);
  HttpResponse responsePOST = client.execute(post);  
  HttpEntity resEntity = responsePOST.getEntity();

  if (resEntity != null)
  {    
    Log.i("RESPONSE", EntityUtils.toString(resEntity));
  }
}
catch (Exception e)
{
  e.printStackTrace();
}

HTTP POST (File Attached)

File file = new File("path/to/your/file.txt");
try
{
  HttpClient client = new DefaultHttpClient();
  String postURL = "http://www.google.com";
  HttpPost post = new HttpPost(postURL);
  FileBody bin = new FileBody(file);
  MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
  reqEntity.addPart("myFile", bin);
  post.setEntity(reqEntity);

  HttpResponse response = client.execute(post);
  HttpEntity resEntity = response.getEntity();

  if (resEntity != null)
  {    
    Log.i("RESPONSE", EntityUtils.toString(resEntity));
  }
}
catch (Exception e)
{
  e.printStackTrace();
}

위의 예제들중에 GET방식 말고는 그야말로 예제에 불과합니다. POST에는 파라미터를 추가하는 예시가 있고 마지막에는 파일을 첨부하는 과정이 정리되어있습니다. 이를 응용하여 다양한 형태의 서버와의 통신을 구현하실 수 있습니다.

사용자 삽입 이미지

결과를 대충 찍어봤는데 잘 나오는군요.

http://james.apache.org/download.cgi
http://hc.apache.org/downloads.cgi
http://www.softwarepassion.com/android-series-get-post-and-multipart-post-requests/