Category Archives: Android

[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/

[Android] EditText에 자동으로 포커스(Focus)되는것 막기

화면에서 EditText가 있을 경우 엑티비티가 생성되면서 자동으로 포커스가 가는 경우가 있습니다. 사실 경우가 있다기 보다는 무조건 포커스가 갑니다. 이것이 좋게 느껴지지는 않는군요. 자동으로 생기는 포커스를 제거하기 위해서는 다양한 방법을 사용할 수 있지만 다음의 방법이 가장 간단하지 않을까 생각합니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<EditText
android:id="@+id/editText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>

</LinearLayout>

위에서 볼 수 있듯이 가장 바깥에 있는 LinearLayout에 다음의 두개의 옵션을 추가하는것만으로 EditText에 포커스가 자동으로 가는것을 막을 수 있습니다.

android:focusable="true"
android:focusableInTouchMode="true"

위의 옵션은 가장 바깥쪽 엘리먼트인 LinearLayout이 우선적으로 포커스를 받아버림으로써 EditText로 포커스가 가는것을 막는 설정입니다. 원래 LinearLayout은 포커스를 받는 대상이 아니지만 포커스를 받게함과 동시에 LinearLayout은 특성상 포커스를 받아도 티가 나지 않기 때문에 별 문제 없이 사용할 수 있습니다.

만약에 위와 같은 구조로 화면이 구성되지 않아 위의 방법을 구현하기 힘들경우 눈에 보이지 않는 LinearLayout을 하나 추가해 주시면 됩니다.

<LinearLayout
android:id="@+id/linearLayout_focus"
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_width="0px"
android:layout_height="0px"/>

예전에는 엑티비티가 뜨는 순간부터 오른쪽의 모습을 가지던것이 왼쪽과 같이 자동으로 포커스가 가는것이 사라졌습니다.
사용자 삽입 이미지

[좌 : 자동포커스 제거 후 / 우 : 자동포커스 제거 전]

참고: http://stackoverflow.com/questions/1555109/stop-edittext-from-gaining-focus-at-activity-startup