不推荐使用NameValuePair和httpParams,如何解决它?

时间:2016-05-25 04:01:31

标签: java android android-studio

我尝试搜索答案,但没有完整的答案。 代码将从库中选择一个图像并上传到服务器数据库。

现在代码有两个错误。 1. NameValuePair 2. HttpParams

这是我的代码

 @Override
        protected Void doInBackground(Void...params){
            ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
            image.compress(Bitmap.CompressFormat.JPEG,100,byteArrayOutputStream);
            String encodedImage= Base64.encodeToString(byteArrayOutputStream.toByteArray(),Base64.DEFAULT);

            ArrayList <NameValuePair> dataToSend=new ArrayList<>();
            dataToSend.add(new BasicNameValuePair("image",encodedImage));
            dataToSend.add(new BasicNameValuePair("name",name));

            HttpParams httpRequestParams=getHttpRequestParams() ;

            HttpClient client=new DefaultHttpClient(httpRequestParams);
            HttpPost post=new HttpPost();
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid){
            super.onPostExecute(aVoid);
        }
    }

    private HttpParams getHttpRequestParams(){
        HttpParams httpRequestParams=new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpRequestParams,100*30);
        HttpConnectionParams.setSoTimeout(httpRequestParams,1000*30);
        return httpRequestParams;

    }

1 个答案:

答案 0 :(得分:1)

我建议你试试android Volley。我要给你看一个示例代码。您也可以在互联网上搜索其他一些样本。玩它。

 RequestQueue queue = Volley.newRequestQueue(Activity.this);
    StringRequest sr = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                    int success;
                    try {
                        JSONObject object = new JSONObject(s.toString());
                        success = object.getInt("success");
                        Log.wtf("success", String.valueOf(success));
                        Log.wtf("message", object.getString("message"));
                        if(success==1){
                            //do something here
                        }else{
                           //do something here
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                }
            }, new Response.ErrorListener(){
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            volleyError.printStackTrace();
        }
    }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String,String> params = new HashMap<String, String>();
            params.put("id", id);
            return params;
        }
    };queue.add(sr);