上传图像json(压缩base64)从android到web服务php


Upload image in json (compress in base64) from android to web service php

我试图上传一个图像(绘制在base64压缩)作为JSONObject从android到web服务使用PHP。我试图使用HttpURLConnection方法post.

我的代码,在android.

try {
            JSONObject params = new JSONObject();
            params.put("nombre", name);
            params.put("img", imgBase64);
            Log.d("params", params.toString());

            URL url = new URL(urlServer);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            //conn.setReadTimeout(5000);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");

            BufferedOutputStream BuffOut = new BufferedOutputStream(conn.getOutputStream());
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(BuffOut, "UTF-8"));
            writer.write(params.toString());
            writer.close();
            BuffOut.close();

            //open
            conn.connect();
            //do somehting with response
            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader buffr = new BufferedReader(new
                        InputStreamReader(
                        conn.getInputStream()));
                StringBuffer sb = new StringBuffer("");
                String line = "";
                while ((line = buffr.readLine()) != null) {
                    sb.append(line);
                    break;
                }
                Log.d("leer", sb.toString());
                buffr.close();
                conn.disconnect();
                return sb.toString();
            } else {
                Log.d("err","false : " + responseCode);
                return "false : " + responseCode;
            }
        } catch (JSONException e) {
            return " Exception JSON: " + e.getMessage();
        } catch (IllegalStateException e) {
            return " IllegalStateException: " + e.getMessage();
        } catch (UnsupportedEncodingException e) {
            return " UnsupportedEncodingException: " + e.getMessage();
        } catch (ProtocolException e) {
            return " ProtocolException: " + e.getMessage();
        } catch (MalformedURLException e) {
            return " MalformedURLException: " + e.getMessage();
        } catch (IOException e) {
            return " Exception IO: " + e.getMessage();
        } catch (Exception e) {
            return " Exception: " + e.getMessage();
        }

在Logcat我有一个错误,如:协议异常:意外结束的流

在服务器端,php我有:

header('Content-type: application/json');
if($_SERVER['REQUEST_METHOD'] == "POST"){
    if(!empty($_POST['nombre'])&&!empty($_POST['img'])){
         echo json_encode(array('status' => 'ok', 'msg' => "hi ".$_POST['nombre']. " img ".$_POST['img']));
    }
 }

如果您不需要特定的功能或有一些限制,我建议使用网络处理volley的volley主页