Make an HTTP request with android

后端 未结 12 1130
时光取名叫无心
时光取名叫无心 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:17

    Note: The Apache HTTP Client bundled with Android is now deprecated in favor of HttpURLConnection. Please see the Android Developers Blog for more details.

    Add to your manifest.

    You would then retrieve a web page like so:

    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();
    }
    

    I also suggest running it on a separate thread:

    class RequestTask extends AsyncTask{
    
    @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..
    }
    }
    

    See the documentation for more information on response handling and POST requests.

提交回复
热议问题