[android] 안드로이드로 HTTP 요청하기

어디에서나 검색했지만 답변을 찾을 수 없습니다. 간단한 HTTP 요청을 할 수있는 방법이 있습니까? 내 웹 사이트 중 하나에서 PHP 페이지 / 스크립트를 요청하고 싶지만 웹 페이지를 표시하고 싶지 않습니다.

가능하면 백그라운드에서 (BroadcastReceiver에서)하고 싶습니다.



답변

최신 정보

이것은 매우 오래된 답변입니다. 나는 더 이상 아파치의 클라이언트를 추천하지 않을 것이다. 대신 다음 중 하나를 사용하십시오.

원래 답변

우선 네트워크 액세스 권한을 요청하고 매니페스트에 다음을 추가하십시오.

<uses-permission android:name="android.permission.INTERNET" />

그런 다음 가장 쉬운 방법은 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());
    }

별도의 스레드에서 실행하려면 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..
    }
}

그런 다음 다음을 통해 요청할 수 있습니다.

   new RequestTask().execute("http://stackoverflow.com");


답변

Apache HttpClient를 선택해야하는 명백한 이유가 없으면 java.net.URLConnection을 선호해야합니다. 웹에서 사용하는 방법에 대한 많은 예를 찾을 수 있습니다.

원래 게시물 이후로 Android 설명서도 개선되었습니다. http://developer.android.com/reference/java/net/HttpURLConnection.html

우리는 공식 블로그 ( http://android-developers.blogspot.com/2011/09/androids-http-clients.html) 에서 장단점에 대해 이야기했습니다.


답변

참고 : Android와 번들로 제공되는 Apache HTTP 클라이언트는 이제 HttpURLConnection 을 위해 더 이상 사용되지 않습니다 . 자세한 내용은 Android 개발자 블로그 를 참조하십시오.

<uses-permission android:name="android.permission.INTERNET" />매니페스트에 추가 하십시오.

그런 다음 다음과 같이 웹 페이지를 검색하십시오.

URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     readStream(in);
}
finally {
     urlConnection.disconnect();
}

또한 별도의 스레드에서 실행하는 것이 좋습니다.

class RequestTask extends AsyncTask<String, String, String>{

@Override
protected String doInBackground(String... uri) {
    String responseString = null;
    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        if(conn.getResponseCode() == HttpsURLConnection.HTTP_OK){
            // Do normal input or output stream reading
        }
        else {
            response = "FAILED"; // See documentation for more info on response handling
        }
    } 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..
}
}

응답 처리 및 POST 요청에 대한 자세한 내용은 설명서 를 참조하십시오 .


답변

가장 간단한 방법은 Volley 라는 Android 라이브러리를 사용하는 것입니다.

발리는 다음과 같은 이점을 제공합니다.

네트워크 요청의 자동 예약. 여러 개의 동시 네트워크 연결 . 표준 HTTP 캐시 일관성을 갖춘 투명한 디스크 및 메모리 응답 캐싱. 요청 우선 순위 지원. 취소 요청 API. 단일 요청을 취소하거나 취소 할 요청 블록 또는 범위를 설정할 수 있습니다. 재시도 및 백 오프와 같은 사용자 정의가 용이합니다. 네트워크에서 비동기식으로 가져온 데이터로 UI를 올바르게 채울 수있는 강력한 순서입니다. 디버깅 및 추적 도구.

다음과 같이 간단하게 http / https 요청을 보낼 수 있습니다.

        // Instantiate the RequestQueue.
        RequestQueue queue = Volley.newRequestQueue(this);
        String url ="http://www.yourapi.com";
        JsonObjectRequest request = new JsonObjectRequest(url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    if (null != response) {
                         try {
                             //handle your response
                         } catch (JSONException e) {
                             e.printStackTrace();
                         }
                    }
                }
            }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        queue.add(request);

이 경우, 모두 이미 발리에서 수행 했으므로 “백그라운드에서 실행”또는 “캐시 사용”을 고려할 필요가 없습니다.


답변

private String getToServer(String service) throws IOException {
    HttpGet httpget = new HttpGet(service);
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    return new DefaultHttpClient().execute(httpget, responseHandler);

}

문안 인사


답변

실로 :

private class LoadingThread extends Thread {
    Handler handler;

    LoadingThread(Handler h) {
        handler = h;
    }
    @Override
    public void run() {
        Message m = handler.obtainMessage();
        try {
            BufferedReader in =
                new BufferedReader(new InputStreamReader(url.openStream()));
            String page = "";
            String inLine;

            while ((inLine = in.readLine()) != null) {
                page += inLine;
            }

            in.close();
            Bundle b = new Bundle();
            b.putString("result", page);
            m.setData(b);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        handler.sendMessage(m);
    }
}


답변

웹 서비스가 Gson lib를 사용하여 URL을 다시 요청하기 위해 이것을 만들었습니다.

고객:

public EstabelecimentoList getListaEstabelecimentoPorPromocao(){

        EstabelecimentoList estabelecimentoList  = new EstabelecimentoList();
        try{
            URL url = new URL("http://" +  Conexao.getSERVIDOR()+ "/cardapio.online/rest/recursos/busca_estabelecimento_promocao_android");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            if (con.getResponseCode() != 200) {
                    throw new RuntimeException("HTTP error code : "+ con.getResponseCode());
            }

            BufferedReader br = new BufferedReader(new InputStreamReader((con.getInputStream())));
            estabelecimentoList = new Gson().fromJson(br, EstabelecimentoList.class);
            con.disconnect();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return estabelecimentoList;
}