Make an HTTP request with android

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

    With a thread:

    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);
        }
    }
    
    0 讨论(0)
  • 2020-11-21 07:22

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

    implementation 'com.android.volley:volley:1.1.1'
    

    Add following into 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.

    0 讨论(0)
  • As none of the answers described a way to perform requests with OkHttp, which is very popular http client nowadays for Android and Java in general, I am going to provide a simple example:

    //get an instance of the client
    OkHttpClient client = new OkHttpClient();
    
    //add parameters
    HttpUrl.Builder urlBuilder = HttpUrl.parse("https://www.example.com").newBuilder();
    urlBuilder.addQueryParameter("query", "stack-overflow");
    
    
    String url = urlBuilder.build().toString();
    
    //build the request
    Request request = new Request.Builder().url(url).build();
    
    //execute
    Response response = client.newCall(request).execute();
    

    The clear advantage of this library is that it abstracts us from some low level details, providing more friendly and secure ways to interact with them. The syntax is also simplified and permits to write nice code.

    0 讨论(0)
  • 2020-11-21 07:24

    This is the new code for HTTP Get/POST request in android. HTTPClient is depricated and may not be available as it was in my case.

    Firstly add the two dependencies in build.gradle:

    compile 'org.apache.httpcomponents:httpcore:4.4.1'
    compile 'org.apache.httpcomponents:httpclient:4.5'
    

    Then write this code in ASyncTask in doBackground method.

     URL url = new URL("http://localhost:8080/web/get?key=value");
     HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
     urlConnection.setRequestMethod("GET");
     int statusCode = urlConnection.getResponseCode();
     if (statusCode ==  200) {
          InputStream it = new BufferedInputStream(urlConnection.getInputStream());
          InputStreamReader read = new InputStreamReader(it);
          BufferedReader buff = new BufferedReader(read);
          StringBuilder dta = new StringBuilder();
          String chunks ;
          while((chunks = buff.readLine()) != null)
          {
             dta.append(chunks);
          }
     }
     else
     {
         //Handle else
     }
    
    0 讨论(0)
  • 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:

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

    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<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");
    
    0 讨论(0)
  • 2020-11-21 07:28

    unless you have an explicit reason to choose the Apache HttpClient, you should prefer java.net.URLConnection. you can find plenty of examples of how to use it on the web.

    we've also improved the Android documentation since your original post: http://developer.android.com/reference/java/net/HttpURLConnection.html

    and we've talked about the trade-offs on the official blog: http://android-developers.blogspot.com/2011/09/androids-http-clients.html

    0 讨论(0)
提交回复
热议问题