Android GET and POST Request

前端 未结 6 1720
执念已碎
执念已碎 2021-02-01 11:14

Can anyone point me to a good implementation of a way to send GET and POST Requests. They are alot of ways to do these, and i am looking for the best implementation. Secondly is

6条回答
  •  梦毁少年i
    2021-02-01 11:54

    I prefer using dedicated class to do GET/POST and any HTTP connections or requests. Moreover I use HttpClient to execute these GET/POST methods.

    Below is sample from my project. I needed thread-safe execution so there is ThreadSafeClientConnManager.

    There is an example of using GET (fetchData) and POST (sendOrder)

    As you can see execute is general method for executing HttpUriRequest - it can be POST or GET.

    public final class ClientHttpClient {
    
    private static DefaultHttpClient client;
    private static CookieStore cookieStore;
    private static HttpContext httpContext;
    
    static {
        cookieStore = new BasicCookieStore();
        httpContext = new BasicHttpContext();
        httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
        client = getThreadSafeClient();
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, AppConstants.CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, AppConstants.SOCKET_TIMEOUT);
        client.setParams(params);
    }
    
    private static DefaultHttpClient getThreadSafeClient() {
        DefaultHttpClient client = new DefaultHttpClient();
        ClientConnectionManager mgr = client.getConnectionManager();
        HttpParams params = client.getParams();
        client = new DefaultHttpClient(new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry()),
                params);
        return client;
    }
    
    private ClientHttpClient() {
    }
    
    public static String execute(HttpUriRequest http) throws IOException {
        BufferedReader reader = null;
        try {
            StringBuilder builder = new StringBuilder();
            HttpResponse response = client.execute(http, httpContext);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            reader = new BufferedReader(new InputStreamReader(content, CHARSET));
            String line = null;
            while((line = reader.readLine()) != null) {
                builder.append(line);
            }
    
            if(statusCode != 200) {
                throw new IOException("statusCode=" + statusCode + ", " + http.getURI().toASCIIString()
                        + ", " + builder.toString());
            }
    
            return builder.toString();
        }
        finally {
            if(reader != null) {
                reader.close();
            }
        }
    }
    
    
    public static List fetchData(Info info) throws JSONException, IOException {
        List out = new LinkedList();
        HttpGet request = buildFetchHttp(info);
        String json = execute(request);
        if(json.trim().length() <= 2) {
            return out;
        }
        try {
            JSONObject responseJSON = new JSONObject(json);
            if(responseJSON.has("auth_error")) {
                throw new IOException("auth_error");
            }
        }
        catch(JSONException e) {
            //ok there was no error, because response is JSONArray - not JSONObject
        }
    
        JSONArray jsonArray = new JSONArray(json);
        for(int i = 0; i < jsonArray.length(); i++) {
            JSONObject chunk = jsonArray.getJSONObject(i);
            ChunkParser parser = new ChunkParser(chunk);
            if(!parser.hasErrors()) {
                out.add(parser.parse());
            }
        }
        return out;
    }
    
    private static HttpGet buildFetchHttp(Info info) throws UnsupportedEncodingException {
        StringBuilder builder = new StringBuilder();
        builder.append(FETCH_TAXIS_URL);
        builder.append("?minLat=" + URLEncoder.encode("" + mapBounds.getMinLatitude(), ENCODING));
        builder.append("&maxLat=" + URLEncoder.encode("" + mapBounds.getMaxLatitude(), ENCODING));
        builder.append("&minLon=" + URLEncoder.encode("" + mapBounds.getMinLongitude(), ENCODING));
        builder.append("&maxLon=" + URLEncoder.encode("" + mapBounds.getMaxLongitude(), ENCODING));
        HttpGet get = new HttpGet(builder.toString());
        return get;
    }
    
    public static int sendOrder(OrderInfo info) throws IOException {
        HttpPost post = new HttpPost(SEND_ORDER_URL);
        List nameValuePairs = new ArrayList(1);
        nameValuePairs.add(new BasicNameValuePair("id", "" + info.getTaxi().getId()));
        nameValuePairs.add(new BasicNameValuePair("address", info.getAddressText()));
        nameValuePairs.add(new BasicNameValuePair("name", info.getName()));
        nameValuePairs.add(new BasicNameValuePair("surname", info.getSurname()));
        nameValuePairs.add(new BasicNameValuePair("phone", info.getPhoneNumber()));
        nameValuePairs.add(new BasicNameValuePair("passengers", "" + info.getPassengers()));
        nameValuePairs.add(new BasicNameValuePair("additionalDetails", info.getAdditionalDetails()));
        nameValuePairs.add(new BasicNameValuePair("lat", "" + info.getOrderLocation().getLatitudeE6()));
        nameValuePairs.add(new BasicNameValuePair("lon", "" + info.getOrderLocation().getLongitudeE6()));
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    
        String response = execute(post);
        if(response == null || response.trim().length() == 0) {
            throw new IOException("sendOrder_response_empty");
        }
    
        try {
            JSONObject json = new JSONObject(response);
            int orderId = json.getInt("orderId");
            return orderId;
        }
        catch(JSONException e) {
            throw new IOException("sendOrder_parsing: " + response);
        }
    }
    

    EDIT

    The execute method is public because sometimes I use custom (or dynamic) GET/POST requests.

    If you have URL object you can pass to execute method:

    HttpGet request = new HttpGet(url.toString());
    execute(request);
    

提交回复
热议问题