티스토리 뷰

[안드로이드] HttpClient 사용하기

1) 안드로이드 앱으로 인터넷 접속을 허용한다.

- 아래의 태그를
<uses-permission android:name="android:name="android.permission.INTERNET" />

2) Get을 하는 방법

public InputStream getInputStreamFromUrl(String url) {
 
InputStream content = null;
  try{
    HttpClient
httpclient = new DefaultHttpClient();
    HttpResponse
response = httpclient.execute(new HttpGet(url));
    content
= response.getEntity().getContent();
  }
catch (Exception e) {
    Log
.("[GET REQUEST]", "Network exception", e);
 
}
  return
content;
}

3) Post를 하는 방법

public void postData() {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("id", "12345"));
        nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
}


4) 위의 소스코드는 AsyncTask에서 실행한다.
* main thread에서 실행하면 android.os.NetworkOnMainThreadException

class HttpTask extends AsyncTask<String , Void , String> {
  protected String doInBackground(String... params)
  {
    InputStream is =
getInputStreamFromUrl(params[0]);

    String result = convertInputStreamToString(is);//이 함수는 이 페이지를 참고

    return result;
  }

  protected void onPostExecute(String result)
  {
    //result를 처리한다.
  }
}


- 위의 클래스를 실행하는 방법은

new HttpTask().execute("http://접근하고자하는URL");

- AsyncTask의 템플릿은 입맛에 따라 바꿔서 사용하면 된다.

끝.


공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함