개발/안드로이드

Android를 사용하여 HTTP 요청 만들기

맨날치킨 2023. 3. 7. 09:06
반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Make an HTTP request with android

Android를 사용하여 HTTP 요청 만들기

 문제 내용 

I have searched everywhere but I couldn't find my answer, is there a way to make a simple HTTP request? I want to request a PHP page / script on one of my websites but I don't want to show the webpage.

여기저기 찾아봤는데 답을 못 찾았는데, 간단한 HTTP 요청을 할 수 있는 방법이 있나요? 제 웹 사이트 중 하나에서 PHP 페이지/스크립트를 요청하고 싶지만 웹 페이지를 표시하고 싶지 않습니다.

 

If possible I even want to do it in the background (in a BroadcastReceiver)

가능하면 백그라운드에서(브로드캐스트리시버에서) 수행하고 싶습니다

 

 

 

 높은 점수를 받은 Solution 

UPDATE

업데이트

 

This is a very old answer. I definitely won't recommend Apache's client anymore. Instead use either:

이것은 아주 오래된 대답이다. 나는 아파치의 고객을 더 이상 추천하지 않을 것이다. 대신 다음 중 하나를 사용합니다:

 

 

Original Answer

원본 답변

 

First of all, request a permission to access network, add following to your manifest:

먼저 네트워크에 액세스할 수 있는 권한을 요청하고 매니페스트에 다음을 참조하십시오:
<uses-permission android:name="android.permission.INTERNET" />

 

Then the easiest way is to use Apache http client bundled with Android:

가장 쉬운 방법은 Android와 함께 제공된 Apache http 클라이언트를 사용하는 것입니다:
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = httpclient.execute(new HttpGet(URL));
    StatusLine statusLine = response.getStatusLine();
    if(statusLine.getStatusCode() == HttpStatus.SC_OK){
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        response.getEntity().writeTo(out);
        String responseString = out.toString();
        out.close();
        //..more logic
    } else{
        //Closes the connection.
        response.getEntity().getContent().close();
        throw new IOException(statusLine.getReasonPhrase());
    }

 

If you want it to run on separate thread I'd recommend extending AsyncTask:

별도의 스레드에서 실행하려면 AsyncTask를 확장하는 것이 좋습니다:
class RequestTask extends AsyncTask<String, String, String>{

    @Override
    protected String doInBackground(String... uri) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response;
        String responseString = null;
        try {
            response = httpclient.execute(new HttpGet(uri[0]));
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                responseString = out.toString();
                out.close();
            } else{
                //Closes the connection.
                response.getEntity().getContent().close();
                throw new IOException(statusLine.getReasonPhrase());
            }
        } catch (ClientProtocolException e) {
            //TODO Handle problems..
        } catch (IOException e) {
            //TODO Handle problems..
        }
        return responseString;
    }
    
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        //Do anything with response..
    }
}

 

You then can make a request by:

그런 다음 다음을 통해 요청할 수 있습니다:
   new RequestTask().execute("http://stackoverflow.com");

 

 

 가장 최근 달린 Solution 

Use Volley as suggested above. Add following into build.gradle (Module: app)

위에서 제안한 대로 발리를 사용하십시오. build.gradle(모듈: app)에 다음을 추가합니다
implementation 'com.android.volley:volley:1.1.1'

 

Add following into AndroidManifest.xml:

AndroidManifest.xml에 다음을 추가합니다:
<uses-permission android:name="android.permission.INTERNET" />

 

And add following to you Activity code:

활동 코드에 다음을 추가합니다:
public void httpCall(String url) {

    RequestQueue queue = Volley.newRequestQueue(this);

    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    // enjoy your response
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // enjoy your error status
                }
    });

    queue.add(stringRequest);
}

 

It replaces http client and it is very simple.

그것은 http 클라이언트를 대체하며 매우 간단합니다.

 

 

 

출처 : https://stackoverflow.com/questions/3505930/make-an-http-request-with-android

반응형