Make an HTTP request with android

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

    For me, the easiest way is using library called Retrofit2

    We just need to create an Interface that contain our request method, parameters, and also we can make custom header for each request :

        public interface MyService {
    
          @GET("users/{user}/repos")
          Call<List<Repo>> listRepos(@Path("user") String user);
    
          @GET("user")
          Call<UserDetails> getUserDetails(@Header("Authorization") String   credentials);
    
          @POST("users/new")
          Call<User> createUser(@Body User user);
    
          @FormUrlEncoded
          @POST("user/edit")
          Call<User> updateUser(@Field("first_name") String first, 
                                @Field("last_name") String last);
    
          @Multipart
          @PUT("user/photo")
          Call<User> updateUser(@Part("photo") RequestBody photo, 
                                @Part("description") RequestBody description);
    
          @Headers({
            "Accept: application/vnd.github.v3.full+json",
            "User-Agent: Retrofit-Sample-App"
          })
          @GET("users/{username}")
          Call<User> getUser(@Path("username") String username);    
    
        }
    

    And the best is, we can do it asynchronously easily using enqueue method

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

    The most simple way is using the Android lib called Volley

    Volley offers the following benefits:

    Automatic scheduling of network requests. Multiple concurrent network connections. Transparent disk and memory response caching with standard HTTP cache coherence. Support for request prioritization. Cancellation request API. You can cancel a single request, or you can set blocks or scopes of requests to cancel. Ease of customization, for example, for retry and backoff. Strong ordering that makes it easy to correctly populate your UI with data fetched asynchronously from the network. Debugging and tracing tools.

    You can send a http/https request as simple as this:

            // 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);
    

    In this case, you needn't consider "running in the background" or "using cache" yourself as all of these has already been done by Volley.

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

    Look at this awesome new library which is available via gradle :)

    build.gradle: compile 'com.apptakk.http_request:http-request:0.1.2'

    Usage:

    new HttpRequestTask(
        new HttpRequest("http://httpbin.org/post", HttpRequest.POST, "{ \"some\": \"data\" }"),
        new HttpRequest.Handler() {
          @Override
          public void response(HttpResponse response) {
            if (response.code == 200) {
              Log.d(this.getClass().toString(), "Request successful!");
            } else {
              Log.e(this.getClass().toString(), "Request unsuccessful: " + response);
            }
          }
        }).execute();
    

    https://github.com/erf/http-request

    0 讨论(0)
  • 2020-11-21 07:16
    private String getToServer(String service) throws IOException {
        HttpGet httpget = new HttpGet(service);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        return new DefaultHttpClient().execute(httpget, responseHandler);
    
    }
    

    Regards

    0 讨论(0)
  • 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 <uses-permission android:name="android.permission.INTERNET" /> 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<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..
    }
    }
    

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

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

    I made this for a webservice to requerst on URL, using a Gson lib:

    Client:

    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;
    }
    
    0 讨论(0)
提交回复
热议问题