Make an HTTP request with android

后端 未结 12 1089
时光取名叫无心
时光取名叫无心 2020-11-21 06:38

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 do

12条回答
  •  迷失自我
    2020-11-21 07:28

    UPDATE

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

    • OkHttp
    • HttpUrlConnection

    Original Answer

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

    
    

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

        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:

    class RequestTask extends AsyncTask{
    
        @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");
    

提交回复
热议问题