如何从HTTPClient升级到凌空

时间:2017-06-08 12:12:24

标签: java android android-volley

在这个类中,我通过使用HttpClient扩展AsyncTask异步向服务器发送请求,我创建了两个自定义类,一个用于从服务器上载和下载映像,另一个用于发送JSON对象和数组。除此之外,我还可以使用 RequestTag

来区分请求

我们也可以使用凌空来做同样的事吗?

如何从具有相同方法的HttpClient升级到Volley,如下面的类?


package com.creative.projectmanager;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;

import org.apache.commons.logging.Log;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
/**
 * server manager class. performs all server requests asynchronously
 */
public class ServerManager {


    final private String SERVER_ADDRESS = "http://192.168.200.10/";


    public void login(String email, String password, int requestTag) {
        String url = SERVER_ADDRESS + "index.php?mobile/" + "login";
        HashMap<String, String> params = new HashMap<>();
        params.put("email", email);
        params.put("password", password);
        params.put("authenticate", "false");
        android.util.Log.w("My App", email + " " + password + " " + requestTag);
        AsyncHttpPost requestSender = new AsyncHttpPost(url, params, requestTag);
        requestSender.execute();
    }
    public void downloadImage(String imageUrl, int imageSize, int requestTag) {
        ImageDownloadTask imageDownloadTask = new ImageDownloadTask(imageUrl, imageSize, requestTag);
        imageDownloadTask.execute();
    }
    private class AsyncHttpPost extends AsyncTask<Void, Void, String> {
        private String url = "";
        private HashMap<String, String> postParams = null;
        private int requestTag;
        private String errorMessage = "";

        public AsyncHttpPost(String url, HashMap<String, String> params, int tag) {
            this.url = url;
            postParams = params;
            this.requestTag = tag;
        }

        @Override
        protected String doInBackground(Void... params) {
            byte[] result;
            String resultString = "";



            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            try {
                ArrayList<NameValuePair> nameValuePairs = new ArrayList<>();
                for (String key:postParams.keySet()
                     ) {
                    nameValuePairs.add(new BasicNameValuePair(key, postParams.get(key)));
                }
                android.util.Log.w("My App",nameValuePairs.toString());
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
                HttpResponse response = httpClient.execute(httpPost);
                StatusLine statusLine = response.getStatusLine();

                if (statusLine.getStatusCode() == HttpURLConnection.HTTP_OK) {
                    errorMessage = "ok";
                    result = EntityUtils.toByteArray(response.getEntity());
                    resultString = new String(result, "UTF-8");
                }
            }
            catch (UnsupportedEncodingException e) {
                errorMessage = "Encoding is not supported";
            }
            catch (Exception e) {
                errorMessage = "An error occurred";
            }
            return resultString;

        }

        @Override
        protected void onPostExecute(String s) {
            if (errorMessage.equals("ok")) {
                sourceActivity.requestFinished(s, requestTag);
            }
            else
                sourceActivity.requestFailed(errorMessage, requestTag);
        }
    }

    private class ImageDownloadTask extends AsyncTask<String, String, String> {
        private String imageUrl;
        private int imageSize;
        private int requestTag;
        Bitmap image;
        public ImageDownloadTask(String imageUrl, int imageSize, int requestTag) {
            this.imageUrl = imageUrl;
            this.imageSize = imageSize;
            this.requestTag = requestTag;
        }
        @Override
        protected String doInBackground(String... params) {
            try {
                URL url = new URL(imageUrl);
                InputStream inputStream = new BufferedInputStream(url.openStream());
                image = createScaledBitmapFromStream(inputStream, imageSize);
            }
            catch (Exception e){
                //do nothing
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            sourceActivity.imageDownloaded(image, requestTag);
        }
        protected Bitmap createScaledBitmapFromStream(InputStream inputStream, int minimumDesiredBitmapSize) {
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream, 32*1024);
            try {
                BitmapFactory.Options decodeBitmapOptions = new BitmapFactory.Options();
                if (minimumDesiredBitmapSize > 0) {
                    BitmapFactory.Options decodeBoundsOptions = new BitmapFactory.Options();
                    decodeBoundsOptions.inJustDecodeBounds = true;
                    bufferedInputStream.mark(32 * 1024);
                    BitmapFactory.decodeStream(bufferedInputStream, null, decodeBoundsOptions);
                    bufferedInputStream.reset();
                    int originalWidth = decodeBoundsOptions.outWidth;
                    int originalHeight = decodeBoundsOptions.outHeight;
                    decodeBitmapOptions.inSampleSize = Math.max(1, Math.min(originalWidth/minimumDesiredBitmapSize, originalHeight/minimumDesiredBitmapSize));
                }
                return BitmapFactory.decodeStream(bufferedInputStream, null, decodeBitmapOptions);
            }
            catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                try {
                    bufferedInputStream.close();
                } catch (IOException ignored) {}
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

有很多关于如何使用Volley提出请求的例子,所以&#34;升级&#34;将意味着以不同的方式重写您的代码。

Volley,在我看来不是最好的HTTP调用库,我建议你试试 http://square.github.io/retrofit/ 加载图像使用http://square.github.io/picasso/或滑行。这些库将帮助您使代码更清晰,从而消除样板内容。