android将编码图像发送到webservice无法正常工作

时间:2016-01-27 20:03:43

标签: android

我已经创建了一个教程(其中很多)如何在选择图库后上传它被证明并不难,但在尝试了一段时间后得到它修复问题的来源证明是在发送时编码图像到Web服务。我已经使用在线解码图像字符串单独测试Web服务,它可以创建奇迹,但是当我从android发送字符串时,它只会出现错误并导致应用程序崩溃。
android代码

    import android.app.ProgressDialog;
    import android.content.Context;
    import android.content.Intent;
    import android.database.Cursor;
    import android.graphics.Bitmap;
    import android.graphics.drawable.BitmapDrawable;
    import android.net.Uri;
    import android.os.AsyncTask;
    import android.provider.MediaStore;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Base64;
    import android.util.Log;
    import android.util.Pair;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ImageView;
    import android.widget.Toast;

    import org.apache.http.params.HttpParams;
    import org.json.JSONException;
    import org.json.JSONObject;

    import java.io.BufferedReader;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private static final int RESULT_LOAD_IMG = 1;

ImageView uploadMe, downloadMe;
Button buttonUp, buttonDown;
EditText textUp, textDown;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    uploadMe = (ImageView) findViewById(R.id.imageToUpload);
    downloadMe = (ImageView) findViewById(R.id.imageToDownload);

    buttonUp = (Button) findViewById(R.id.buttonUploadImage);
    buttonDown = (Button) findViewById(R.id.buttonDownloadImage);

    textUp = (EditText) findViewById(R.id.uploadName);
    textDown = (EditText) findViewById(R.id.downloadName);

    uploadMe.setOnClickListener(this);
    buttonUp.setOnClickListener(this);
    buttonDown.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    switch (v.getId())
    {
        case R.id.imageToUpload:
            Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
            break;
        case R.id.buttonUploadImage:
            Bitmap image = ((BitmapDrawable) uploadMe.getDrawable()).getBitmap();

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            image.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
            String encodedImage = Base64.encodeToString(byteArrayOutputStream.toByteArray(), Base64.DEFAULT);

            String URL = "URL TO PHP FILE/upload_image.php?image=" + encodedImage + "&name=" + textUp.getText().toString(); //crashes when i send the string here
            new JSONTask().execute(URL);
            break;
        case R.id.buttonDownloadImage:

            break;
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && data != null)
    {
        Uri selectedImg = data.getData();
        uploadMe.setImageURI(selectedImg);
    }
}

public class JSONTask extends AsyncTask<String, Void, Void>
{
    String error, content;

    @Override
    protected Void doInBackground(String... params) {
        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try
        {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            InputStream stream = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();

            String line = "";
            while ((line = reader.readLine()) != null)
            {
                buffer.append(line);
            }

            content = buffer.toString();
        }
        catch (MalformedURLException e)
        {
            error = e.getMessage();
            e.printStackTrace();
        }
        catch (IOException e)
        {
            error = e.getMessage();
            e.printStackTrace();
        }
        finally
        {
            if (connection != null)
                connection.disconnect();
            try
            {
                if (reader != null)
                    reader.close();
            }
            catch(IOException e)
            {
                e.printStackTrace();
            }
        }
        return null;
    }

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

        if (error != null)
        {
            Log.d("JSON", error);
        }
        else
        {
            String output = "";

            JSONObject jsonResponse;

            try
            {
                jsonResponse = new JSONObject(content);

                Toast.makeText(MainActivity.this, jsonResponse.getString("success"), Toast.LENGTH_SHORT).show();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
}


}

我试图解决它,但它只是弄乱了一切。有没有办法解决这个问题而不改变一切?也许只是连接类 的堆栈跟踪

01-27 21:21:47.232 4205-4205/com.blablabla.exportimagetest D/dalvikvm: 

GC_FOR_ALLOC freed 9429K, 31% free 17075K/24628K, paused 0ms, total 0ms
01-27 21:21:47.242 4205-4205/com.blablabla.exportimagetest D/dalvikvm: GC_FOR_ALLOC freed 2341K, 23% free 19115K/24628K, paused 10ms, total 10ms
01-27 21:21:47.342 4205-4221/com.blablabla.exportimagetest D/dalvikvm: GC_FOR_ALLOC freed 5395K, 17% free 18628K/22240K, paused 0ms, total 0ms
01-27 21:21:47.392 4205-4221/com.blablabla.exportimagetest D/dalvikvm: GC_FOR_ALLOC freed 2071K, 18% free 19436K/23696K, paused 0ms, total 0ms
01-27 21:21:47.482 4205-4221/com.blablabla.exportimagetest D/dalvikvm: GC_FOR_ALLOC freed 2707K, 18% free 21144K/25576K, paused 0ms, total 0ms
01-27 21:21:47.492 4205-4221/com.blablabla.exportimagetest D/dalvikvm: GC_FOR_ALLOC freed 3155K, 19% free 22399K/27456K, paused 0ms, total 0ms
01-27 21:21:47.512 4205-4221/com.blablabla.exportimagetest D/dalvikvm: GC_FOR_ALLOC freed 4382K, 24% free 22399K/29336K, paused 0ms, total 0ms
01-27 21:21:49.602 4205-4221/com.blablabla.exportimagetest W/System.err: java.io.EOFException
01-27 21:21:49.602 4205-4221/com.blablabla.exportimagetest W/System.err:     at com.android.okhttp.internal.Util.readAsciiLine(Util.java:318)
01-27 21:21:49.602 4205-4221/com.blablabla.exportimagetest W/System.err:     at com.android.okhttp.internal.http.RawHeaders.fromBytes(RawHeaders.java:308)
01-27 21:21:49.602 4205-4221/com.blablabla.exportimagetest W/System.err:     at com.android.okhttp.internal.http.HttpTransport.readResponseHeaders(HttpTransport.java:135)
01-27 21:21:49.602 4205-4221/com.blablabla.exportimagetest W/System.err:     at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:644)
01-27 21:21:49.602 4205-4221/com.blablabla.exportimagetest W/System.err:     at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:347)
01-27 21:21:49.602 4205-4221/com.blablabla.exportimagetest W/System.err:     at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:296)
01-27 21:21:49.602 4205-4221/com.blablabla.exportimagetest W/System.err:     at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:179)
01-27 21:21:49.602 4205-4221/com.blablabla.exportimagetest W/System.err:     at com.blablabla.exportimagetest.MainActivity$JSONTask.doInBackground(MainActivity.java:116)
01-27 21:21:49.602 4205-4221/com.blablabla.exportimagetest W/System.err:     at com.blablabla.exportimagetest.MainActivity$JSONTask.doInBackground(MainActivity.java:101)
01-27 21:21:49.602 4205-4221/com.blablabla.exportimagetest W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:288)
01-27 21:21:49.602 4205-4221/com.blablabla.exportimagetest W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
01-27 21:21:49.602 4205-4221/com.blablabla.exportimagetest W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
01-27 21:21:49.602 4205-4221/com.blablabla.exportimagetest W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
01-27 21:21:49.602 4205-4221/com.blablabla.exportimagetest W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
01-27 21:21:49.602 4205-4221/com.blablabla.exportimagetest W/System.err:     at java.lang.Thread.run(Thread.java:841)
01-27 21:21:49.612 4205-4205/com.blablabla.exportimagetest W/System.err: java.lang.NullPointerException
01-27 21:21:49.612 4205-4205/com.blablabla.exportimagetest W/System.err:     at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
01-27 21:21:49.612 4205-4205/com.blablabla.exportimagetest W/System.err:     at org.json.JSONTokener.nextValue(JSONTokener.java:94)
01-27 21:21:49.612 4205-4205/com.blablabla.exportimagetest W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:155)
01-27 21:21:49.612 4205-4205/com.blablabla.exportimagetest W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:172)
01-27 21:21:49.612 4205-4205/com.blablabla.exportimagetest W/System.err:     at com.blablabla.exportimagetest.MainActivity$JSONTask.onPostExecute(MainActivity.java:172)
01-27 21:21:49.612 4205-4205/com.blablabla.exportimagetest W/System.err:     at com.blablabla.exportimagetest.MainActivity$JSONTask.onPostExecute(MainActivity.java:101)
01-27 21:21:49.612 4205-4205/com.blablabla.exportimagetest W/System.err:     at android.os.AsyncTask.finish(AsyncTask.java:632)
01-27 21:21:49.612 4205-4205/com.blablabla.exportimagetest W/System.err:     at android.os.AsyncTask.access$600(AsyncTask.java:177)
01-27 21:21:49.612 4205-4205/com.blablabla.exportimagetest W/System.err:     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
01-27 21:21:49.612 4205-4205/com.blablabla.exportimagetest W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
01-27 21:21:49.612 4205-4205/com.blablabla.exportimagetest W/System.err:     at android.os.Looper.loop(Looper.java:136)
01-27 21:21:49.612 4205-4205/com.blablabla.exportimagetest W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5021)
01-27 21:21:49.612 4205-4205/com.blablabla.exportimagetest W/System.err:     at java.lang.reflect.Method.invokeNative(Native Method)
01-27 21:21:49.612 4205-4205/com.blablabla.exportimagetest W/System.err:     at java.lang.reflect.Method.invoke(Method.java:515)
01-27 21:21:49.612 4205-4205/com.blablabla.exportimagetest W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:827)
01-27 21:21:49.612 4205-4205/com.blablabla.exportimagetest W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:643)
01-27 21:21:49.612 4205-4205/com.blablabla.exportimagetest W/System.err:     at dalvik.system.NativeStart.main(Native Method)

修改

HttpURLConnection connection = null;
        BufferedReader reader = null;
        String urlParms = "image=" + encodedImage + "&name=" + nameValue;
        byte[] postData       = urlParms.getBytes( StandardCharsets.UTF_8 );
        int    postDataLength = postData.length;

        try
        {
            URL url = new URL("http://192.168.1.2/web%20service%20owner_tenant/upload_image.php");
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("charset", "utf-8");
            connection.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));

            DataOutputStream wr = new DataOutputStream( connection.getOutputStream());
                wr.write(postData);
                wr.flush();
                wr.close();

            connection.connect();

            InputStream stream = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();

            String line = "";
            while ((line = reader.readLine()) != null)
            {
                buffer.append(line);
            }

            content = buffer.toString();

PHP脚本

<?php
//array for JSON response
$response = array();

require_once __DIR__ . '/connect.php';
$cnx = new DB_Connect();
$db = $cnx->connectMe();

if (!empty($_REQUEST['name']) && $_REQUEST['name'] != null
    && !empty($_REQUEST['image']) && $_REQUEST['image'] != null)
{   
    $name = $_REQUEST['name'];
    $image = $_REQUEST['image'];
    $response['error'] = "A | ";
    $decodedImage = base64_decode("$image");
    if (!$file = fopen("pictures/" . $name . ".PNG", 'wb')) {
        $response['error'] .= 'Failed to open | ';
    }
    if (fwrite($file, $decodedImage) === FALSE) {
        $response['error'] .= 'Failed to write';
    }
    fclose($file);

    //will be handled to correct response as later
    $response['success'] = '1';
    echo json_encode($response);
}
else
{
    $response['success'] = '0';
    $response['message'] = 'Missing or Empty Parameter(s)';
    echo json_encode($response);
}
?>


更新
我在上一次运行中遇到了Web服务的最后一个错误,我必须添加这个

    $image = str_replace(' ', '+', $image);

1 个答案:

答案 0 :(得分:1)

您将图像放在GET请求的url参数中。这不会做,因为你只能在网址中发送少量字节。你应该使用POST方法。