排球邮件请求未正确发送数据

时间:2016-12-03 09:39:34

标签: android http-post android-volley

我正在尝试通过齐射将一个base64编码的字符串发送到服务器,但它没有正确发送。当我使用httpbin时,这就是响应 “args”:{},

I/System.out:   "data": "", 
I/System.out:   "files": {}, 
I/System.out:   "form": {  "/9j/4AAQSkZJRgABAQAASABIAAD/4QBMRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAAqACAAQAAAABAAACiaADAAQAAAABAAAARQAAAAD/4QkhaHR0cDovL25zLmFkb2JlLmN...(image base64)
I/System.out:   }, 

图像数据在表单中。但是我需要它在数据中。

public static String rawOutput = "dadsdas";
    private Button buttonChoose;
    private Button buttonUpload;
public String image;
    private ImageView imageView;
    private Button postText;

    private EditText editTextName;

    private Bitmap bitmap;

    private int PICK_IMAGE_REQUEST = 1;

    private String UPLOAD_URL ="https://httpbin.org/post";

    private String KEY_IMAGE = "Content-Type";
    private String KEY_NAME = "name";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post_image);
        buttonChoose = (Button) findViewById(R.id.buttonChoose);
         postText = (Button) findViewById(R.id.postText);
        buttonUpload = (Button) findViewById(R.id.buttonUpload);
        imageView  = (ImageView) findViewById(R.id.imageView);
        buttonChoose.setOnClickListener(this);
        buttonUpload.setOnClickListener(this);
    }

    public String getStringImage(Bitmap bmp){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 50, baos);
        byte[] imageBytes = baos.toByteArray();
        System.out.println(imageBytes);
        String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
        return encodedImage;
    }

    private void uploadImage() throws JSONException {
        //Showing the progress dialog
        final ProgressDialog loading = ProgressDialog.show(this,"Uploading...","Please wait...",false,false);
//        JSONObject jsonBody = new JSONObject();
//        jsonBody.put(getStringImage(bitmap), "");
        //final String mRequestBody = jsonBody.toString();
        StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        loading.dismiss();
                        System.out.println(s);
                        Toast.makeText(PostImage.this, s , Toast.LENGTH_LONG).show();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        loading.dismiss();
                        String json = null;

                        NetworkResponse response = volleyError.networkResponse;
                        if(response != null && response.data != null){
                            switch(response.statusCode){
                                case 400:

                                    json = new String(response.data);
                                    if(json != null) System.out.println(json);
                                    System.out.println(json.getClass().getSimpleName());
                                    break;
                            }
                            //Additional cases
                        }
                        Toast.makeText(PostImage.this, volleyError.getMessage(), Toast.LENGTH_LONG).show();
                    }
                }){
//            @Override
//            public String getBodyContentType() {
//                return "text/plain; charset=utf-8";
//            }
//            @Override
//            public byte[] getBody() {
//                byte[] body = new byte[0];
//                try {
//                    body = ("/9j/4AAQSkZJRgABAQAASABIAAD/4QBMRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAAqACAAQAAAABAAACiaADAAQAAAABAAAARQAAAAD/4QkhaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/PiA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJYTVAgQ29yZSA1LjQuMCI+IDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+IDxyZGY6RGVz.......(image data here)");
//
                    //} catch (UnsupportedEncodingException exception) {
                     //   Log.e("ERROR", "exception", exception);
                        // return null and don't pass any POST string if you encounter encoding error
                    //return null;
                    //}
                    return httpPostBody.getBytes();
                }

//            @Override
//            public String getBody() throws AuthFailureError {
//                image = getStringImage(bitmap);
//                System.out.printf(image);
//                String params= "";
//                params=  image;
//                return params;
//
//            }
//            @Override
//            protected Map<String, String> getParams() throws AuthFailureError {
//                image = getStringImage(bitmap);
//                System.out.printf(image);
//                Map<String,String> params = new Hashtable<String, String>();
//                params.put("", image);
//                return params;
//            }


            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
                return params;
            }
        };
        //Creating a Request Queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        //Adding request to the queue
        requestQueue.add(stringRequest);
        System.out.println(stringRequest);
    }

    private void showFileChooser() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            Uri filePath = data.getData();
            try {
                //Getting the Bitmap from Gallery
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                //Setting the Bitmap to ImageView
                imageView.setImageBitmap(bitmap);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    public void onClick(View v) {

        if(v == buttonChoose){
            showFileChooser();
        }
        if(v == buttonUpload){
            try {
                uploadImage();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    public void postText(View v) {
        try {
            RequestQueue requestQueue = Volley.newRequestQueue(this);
            String URL = "http://api.getquesto.com:8080/upload";
            JSONObject jsonBody = new JSONObject();
            jsonBody.put("Text:", "A leaf is an organ of a vascular plant and is the principal lateral appendage of the stem.[1] The leaves and stem together form the shoot.[2] Leaves are collectively referred to as foliage, as in \"autumn foliage.\"[3][4]\n" +
                    "\n" +
                    "\n" +
                    "Diagram of a simple leaf.\n" +
                    "Apex Midvein (Primary vein) Secondary vein. Lamina. Leaf margin Petiole Bud Stem\n" +
                    "Although leaves can be seen in many different textures and sizes, typically a leaf is a thin, dorsiventrally flattened organ, borne above ground and specialized for photosynthesis. In most leaves, the primary photosynthetic tissue, the (palisade mesophyll), is located on the upper side of the blade or lamina of the leaf[1] but in some species, including the mature foliage of Eucalyptus,[5] palisade mesophyll is present on both sides and the leaves are said to be isobilateral. Most leaves have distinctive upper (adaxial) and lower (abaxial) surfaces that differ in colour, hairiness, the number of stomata (pores that intake and output gases), epicuticular wax amount and structure and other features.\n" +
                    "\n" +
                    "Broad, flat leaves with complex venation are known as megaphylls and the species that bear them, the majority, as broad-leaved or megaphyllous plants. In others, such as the clubmosses, with different evolutionary origins, the leaves are simple, with only a single vein and are known as microphylls.[6]\n" +
                    "\n" +
                    "Some leaves, such as bulb scales are not above ground, and in many aquatic species the leaves are submerged in water. Succulent plants often have thick juicy leaves, but some leaves are without major photosynthetic function and may be dead at maturity, as in some cataphylls, and spines). Furthermore, several kinds of leaf-like structures found in vascular plants are not totally homologous with them. Examples include flattened plant stems called phylloclades and cladodes, and flattened leaf stems called phyllodes which differ from leaves both in their structure and origin.[4][7] Many structures of non-vascular plants, such as the phyllids of mosses and liverworts and even of some foliose lichens, which are not plants at all (in the sense of being members of the kingdom Plantae), look and function much like leaves.");
            final String mRequestBody = jsonBody.toString();
            String json = null;
            StringRequest stringRequest = new StringRequest(POST, URL, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.i("VOLLEY", response);

                    Toast.makeText(PostImage.this, response , Toast.LENGTH_LONG).show();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("VOLLEY", error.toString());
                }
            }) {
                @Override
                public String getBodyContentType() {
                    return "application/json; charset=utf-8";
                }

                @Override
                public byte[] getBody() throws AuthFailureError {
                    try {
                        return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
                    } catch (UnsupportedEncodingException uee) {
                        VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
                        return null;
                    }
                }
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String> params = new HashMap<>();
                    params.put("Content-Type","text/plain");
                    return params;
                }
                @Override
                protected Response<String> parseNetworkResponse(NetworkResponse response) {
                    String responseString = "";
                    if (response != null) {
                        responseString = String.valueOf(response.statusCode);
                        // can get more details such as response.headers
                    }
                    return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
                }
            };

            requestQueue.add(stringRequest);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}`

有谁知道如何通过数据发送?

0 个答案:

没有答案