通过从Android的HTTP POST请求发送的Base64连接codeD映像映像、HTTP、Android、POST

2023-09-06 05:25:24 作者:○﹋言兑聲尒好~

我完全失去了,我试图通过Android应用程序将照片发送给一个PHP网页。

Theoritically一切都应该是正确的,但目标数据损坏或东西,我不知道......

我能得到这个职位数据,我试着用它工作得很好一个简单的字符串,但带着沉重的文件中的数据似乎已损坏。

 公共类EncodingAndSending继承Thread {
    ShareOnMyWebSiteActivity mycontext;
    ContentResolver的铬;
    乌里URI;
    公开处理程序mainHandler,sHandler;

    公共EncodingAndSending(ShareOnMyWebSiteActivity myctxt,处理程序铭万,开放的URI,ContentResolver的CRR){
         mycontext = myctxt;
         CR = CRR;
         URI = URI;
         mainHandler =铭万;
         this.start();
    }

        返回buffer.toString()与toUpperCase()。
      }

    公共无效的run(){

        InputStream的是= NULL;
        byte []的数据= NULL;
        尝试 {
            是= cr.openInputStream(URI);
             //获取连接code二进制字节
            数据= getFileBytes(是);
        }赶上(例外E1){
            // TODO自动生成的catch块
            e1.printStackTrace();
        }

        字符串data_string = Base64.en codeToString(数据,Base64.URL_SAFE);


        如果(data_string!=){
            sendRequest将(data_string);
        }
        其他{

        }

    }

公共字节[] getFileBytes(InputStream的IOS)抛出IOException异常{
            ByteArrayOutputStream的OU = NULL;
            // InputStream的IOS = NULL;
            尝试 {
                byte []的缓冲区=新的字节[4096];
                的OU =新ByteArrayOutputStream();
                // IOS =新的FileInputStream(文件);
                INT读= 0;
                而((读= ios.read(缓冲))!= -1)
                    ous.write(缓冲,0,读);
            } 最后 {
                尝试 {
                    如果(OU中!= NULL)
                        ous.close();
                }赶上(IOException异常E){
                    //燕子,因为没有那么重要
                }
                尝试 {
                    如果(IOS!= NULL)
                        ios.close();
                }赶上(IOException异常E){
                    //燕子,因为没有那么重要
                }
            }
            返回ous.toByteArray();
        }


    私人无效sendRequest将(字符串data_string){

        HttpClient的HttpClient的=新DefaultHttpClient();
        HttpPost httppost =新HttpPost(xxxxx.php);

        尝试 {

            名单<的NameValuePair> namevaluepairs中=新的ArrayList<的NameValuePair>(2);
            nameValuePairs.add(新BasicNameValuePair(形象,data_string));

            httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中));

            //执行HTTP POST请求
            HTT presponse响应= httpclient.execute(httppost);
            ResponseHandler的<字符串> ResponseHandler的=新BasicResponseHandler();
            字符串responseBody = httpclient.execute(httppost,ResponseHandler所);


        }赶上(例外五){
            // TODO自动生成的catch块
        }
    }

}
 

编辑:

这工作。我可以连接code和德code和preVIEW图像。我没有需要使用getBytes()函数,我不知道,如果问题出自那里。

我会告诉你的。

  super.onCreate(savedInstanceState);
    的setContentView(R.layout.test_image);
    ImageView的形象=(ImageView的)findViewById(R.id.imageView1);
    在的FileInputStream;
    的BufferedInputStream BUF;

    意向意图= getIntent();
    捆绑额外= intent.getExtras();

    开放的我们的uri =(URI)extras.getParcelable(Intent.EXTRA_STREAM);
    ContentResolver的CR = getContentResolver();
    位图BMAP = NULL;
    尝试 {
        InputStream的是= cr.openInputStream(URI);

        BMAP = BitmapFactory.de codeStream(是);

        如果(是!= NULL){
        is.close();
        }
    }赶上(例外五){
        Log.e(读取文件错误,e.toString());
    }

    ByteArrayOutputStream BAOS =新ByteArrayOutputStream();
    bMap.com preSS(Bitmap.Com pressFormat.JPEG,100,BAOS);
    byte []的B = baos.toByteArray();
    字符串data_string = Base64.en codeToString(B,Base64.DEFAULT);

    B = NULL; BMAP = NULL;
    B = Base64.de code(data_string,Base64.DEFAULT);
    BMAP = BitmapFactory.de codeByteArray(B,0,b.length个);
    image.setImageBitmap(BMAP);
 
使用OkHttp发送POST请求的快速入门指南

解决方案

我写了一个小的应用程序,允许发送与手机的摄像头拍摄到一个数据库中的图像。以下是我解决了这个事情...

 公共无效writeCommentForRestaurant(INT ID,字符串注释,字符串作者,
        位图图像){

    如果(图像!= NULL){
        / *获取的图像作为字符串* /
        // 正常
        ByteArrayOutputStream full_stream =新ByteArrayOutputStream();
        image.com preSS(Bitmap.Com pressFormat.PNG,100,full_stream);
        byte []的full_bytes = full_stream.toByteArray();
        字符串img_full = Base64.en codeToString(full_bytes,Base64.DEFAULT);
        //缩略图
        ByteArrayOutputStream thumb_stream =新ByteArrayOutputStream();
                    //该getScaledBitmap方法只减少了位图的一个小图标!
        getScaledBitmap(图像,72).COM preSS(Bitmap.Com pressFormat.JPEG,75,
                thumb_stream);
        byte []的thumb_bytes = thumb_stream.toByteArray();
        字符串img_thumbnail = Base64.en codeToString(thumb_bytes,Base64.DEFAULT);

        //新HTTPWorker(CTX,mHandler,HTTPWorker.WRITE_COMMENT,真).execute(
        // Integer.toString(ID),注释,作者,img_thumbnail,img_full);
    } 其他 {
        //新HTTPWorker(CTX,mHandler,HTTPWorker.WRITE_COMMENT,真).execute(
        // Integer.toString(ID),注释,作者,NULL,NULL);
    }
}
 

该HTTPWorker就是这样构建HTTPmethod。

这是AsyncTask的

  ...
/ *添加参数* /
arguments.add(新BasicNameValuePair(idrestaurant,则params [0]));
arguments.add(新BasicNameValuePair(意见,则params [1]));
arguments.add(新BasicNameValuePair(作家,则params [2]));
如果(params.length→3){
  arguments.add(新BasicNameValuePair(形象,则params [3]));
  arguments.add(新BasicNameValuePair(bigimage,则params [4]));
}
...
 

然后,我将它发送到服务器这样的。

  / **
*执行一个httppost到服务器实例与给定的POST参数
*和从服务器返回一个String响应。
* /
私人字符串httppost(字符串URL,ArrayList的<的NameValuePair>的args){
  / *创建渠道communicaton * /
  InputStream的是= NULL;

  / *发送请求给服务器* /
  尝试 {
    / *创建POST * /
    HttpClient的HttpClient的=新DefaultHttpClient();
    HttpPost httppost =新HttpPost(URL);

    / *添加登录信息POST变量在php * /
    httppost.setEntity(新UrlEn codedFormEntity(参数));

    / *执行HTTP POST和GET响应* /
    HTT presponse响应= httpclient.execute(httppost);
    HttpEntity实体= response.getEntity();
    是= entity.getContent();
  }赶上(例外五){
    Log.e(TAG,在HTTP连接错误+ e.toString());
    返回null;
  }

  / *读取来自服务器的响应* /
  尝试 {
    / *读取响应流* /
    的BufferedReader读卡器=新的BufferedReader(新的InputStreamReader(
    是,ISO-8859-1),8);

    / *响应复制到StringBuilder的* /
    StringBuilder的SB =新的StringBuilder();
    串线= NULL;
    而((行= reader.readLine())!= NULL){
      sb.append(行+\ N);
    }
    is.close();

    / *返回的响应,字符串* /
    返回sb.toString();
  }赶上(例外五){
    Log.e(TAG,错误将导致+ e.toString());
    返回null;
  }
}
 

I am completely lost, I am trying to send a photo via an android app to a php webpage.

Theoritically everything should be right but the destination data is corrupted or something I don't know...

I can get the post data, I tried with a simple string it worked fine but with a heavy file the data seems corrupted.

public class EncodingAndSending extends Thread{
    ShareOnMyWebSiteActivity mycontext;
    ContentResolver cr;
    Uri uri;
    public Handler mainHandler,sHandler;

    public EncodingAndSending(ShareOnMyWebSiteActivity myctxt,Handler mainone,Uri URI,ContentResolver crr){
         mycontext=myctxt;
         cr=crr;
         uri=URI;
         mainHandler=mainone;
         this.start();
    }

        return buffer.toString().toUpperCase();    
      }

    public void run(){

        InputStream is=null;
        byte[] data=null;
        try {
            is = cr.openInputStream(uri);
             // Get binary bytes for encode
            data = getFileBytes(is);
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        String data_string=Base64.encodeToString(data,Base64.URL_SAFE);


        if(data_string!=""){
            SendRequest(data_string);
        }
        else{

        }

    }

public byte[] getFileBytes(InputStream ios) throws IOException {
            ByteArrayOutputStream ous = null;
            //InputStream ios = null;
            try {
                byte[] buffer = new byte[4096];
                ous = new ByteArrayOutputStream();
                //ios = new FileInputStream(file);
                int read = 0;
                while ((read = ios.read(buffer)) != -1)
                    ous.write(buffer, 0, read);
            } finally {
                try {
                    if (ous != null)
                        ous.close();
                } catch (IOException e) {
                    // swallow, since not that important
                }
                try {
                    if (ios != null)
                        ios.close();
                } catch (IOException e) {
                    // swallow, since not that important
                }
            }
            return ous.toByteArray();
        }


    private void SendRequest(String data_string){

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("xxxxx.php");

        try {

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("image", data_string));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            ResponseHandler<String> responseHandler=new BasicResponseHandler();
            String responseBody = httpclient.execute(httppost, responseHandler);


        } catch (Exception e) {
            // TODO Auto-generated catch block
        }       
    }

}

EDIT:

This works. I can encode and decode and preview the image. I didn't use the getBytes() function I don't know if the problem comes from there.

I'll let you know.

    super.onCreate(savedInstanceState);
    setContentView(R.layout.test_image);
    ImageView image = (ImageView) findViewById(R.id.imageView1);
    FileInputStream in;
    BufferedInputStream buf;

    Intent intent = getIntent();
    Bundle extras = intent.getExtras();

    Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
    ContentResolver cr = getContentResolver();
    Bitmap bMap=null;
    try {
        InputStream is = cr.openInputStream(uri);

        bMap = BitmapFactory.decodeStream(is);

        if (is != null) {
        is.close();
        }
    } catch (Exception e) {
        Log.e("Error reading file", e.toString());
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();  
    bMap.compress(Bitmap.CompressFormat.JPEG, 100, baos);   
    byte[] b = baos.toByteArray();
    String data_string=Base64.encodeToString(b,Base64.DEFAULT);

    b=null;bMap=null;
    b=Base64.decode(data_string, Base64.DEFAULT);
    bMap=BitmapFactory.decodeByteArray(b, 0, b.length);
    image.setImageBitmap(bMap);

解决方案

I wrote a small app that allowed for sending images taken with the phone's camera to a database. Here's how I solved the thing...

public void writeCommentForRestaurant(int id, String comment, String author,
        Bitmap image) {

    if (image != null) {
        /* Get the image as string */
        // Normal
        ByteArrayOutputStream full_stream = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.PNG, 100, full_stream);
        byte[] full_bytes = full_stream.toByteArray();
        String img_full = Base64.encodeToString(full_bytes, Base64.DEFAULT);
        // Thumbnail
        ByteArrayOutputStream thumb_stream = new ByteArrayOutputStream();
                    // The getScaledBitmap method only minimizes the Bitmap to a small icon!
        getScaledBitmap(image, 72).compress(Bitmap.CompressFormat.JPEG, 75,
                thumb_stream);
        byte[] thumb_bytes = thumb_stream.toByteArray();
        String img_thumbnail = Base64.encodeToString(thumb_bytes, Base64.DEFAULT);

        // new HTTPWorker(ctx, mHandler, HTTPWorker.WRITE_COMMENT, true).execute(
        // Integer.toString(id), comment, author, img_thumbnail, img_full);
    } else {
        // new HTTPWorker(ctx, mHandler, HTTPWorker.WRITE_COMMENT, true).execute(
        // Integer.toString(id), comment, author, null, null);
    }
}

The HTTPWorker is just an asynctask that constructs the HTTPmethod.

...
/* Add arguments */
arguments.add(new BasicNameValuePair("idrestaurant", params[0]));
arguments.add(new BasicNameValuePair("comment", params[1]));
arguments.add(new BasicNameValuePair("author", params[2]));
if (params.length > 3) {
  arguments.add(new BasicNameValuePair("image", params[3]));
  arguments.add(new BasicNameValuePair("bigimage", params[4]));
}
...

And then I sent it to the server like this.

/**
* Executes a httppost to a server instance with the given POST arguments
* and returns a String response from the server.
*/
private String httppost(String url, ArrayList<NameValuePair> args) {
  /* Create the channel for communicaton */
  InputStream is = null;

  /* Send request to server */
  try {
    /* Create the POST */
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);

    /* Add the login information "POST" variables in the php */
    httppost.setEntity(new UrlEncodedFormEntity(args));

    /* Execute the http POST and get the response */
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    is = entity.getContent();
  } catch (Exception e) {
    Log.e(TAG, "Error in http connection " + e.toString());
    return null;
  }

  /* Read response from server */
  try {
    /* Read the response stream */
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    is, "iso-8859-1"), 8);

    /* Copy the response to StringBuilder */
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
      sb.append(line + "\n");
    }
    is.close();

    /* Return the response as string */
    return sb.toString();
  } catch (Exception e) {
    Log.e(TAG, "Error converting result " + e.toString());
    return null;
  }
}