如何在Android上用JSON发送文件?

时间:2013-08-05 04:18:57

标签: android json chunked

我想使用http客户端以JSON方式发送文件我不知道如何启动任何人都可以建议我应该做什么?我将发送有关此JSON格式的数据:

 {
    "Filename": "282850ad-de5c-498f-8280-2d4b6d77b774.jpg",
    "ChunkId":1,
    "ChunkLength":11397,
    "FileLength":11397
 }

如你所见,我将以块状发送文件。我不知道我是否要将文件转换为字节数组。如果我需要,任何人都可以提供一些示例代码谢谢。

3 个答案:

答案 0 :(得分:9)

要在服务器上发送文本文件或图像文件,您可以使用MultiPartEntity。

DefaultHttpClient localDefaultHttpClient = new DefaultHttpClient();

      FileBody localFileBody = new FileBody(new File(this.picturePath), "image/jpg");
      HttpPost localHttpPost = new HttpPost("http://website.com/path/....");
      MultipartEntity localMultipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
      try
      {
        Log.d("picturepath", this.picturePath);
        localMultipartEntity.addPart("Email", new StringBody("emailid@gmail.com"));
        localMultipartEntity.addPart("password", new StringBody("password"));
        localMultipartEntity.addPart("phone", new StringBody("9875......."));
        localMultipartEntity.addPart("profilepicture", localFileBody);
        localHttpPost.setEntity(localMultipartEntity);
        HttpResponse localHttpResponse = localDefaultHttpClient.execute(localHttpPost);
        System.out.println("responsecode" + localHttpResponse.getStatusLine().getStatusCode());
}
catch (Exception e)
      {
        Log.d("exception", e.toString());
      }

这是有效的,因为此代码是我的Running项目的一部分。

答案 1 :(得分:4)

您可以使用MultiPartEntity发送文本文件和媒体文件。

public String SendToServer(String aUrl,File Filename)
{
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(aUrl);

    try 
    {
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        entity.addPart("file", new FileBody(Filename));
        entity.addPart("video-title", new StringBody("Video"));
        entity.addPart("video-type", new StringBody("1"));
        httpPost.setEntity(entity);

        HttpContext context = new BasicHttpContext();
        // Bind custom cookie store to the local context
        context.setAttribute(ClientContext.COOKIE_STORE, Globals.sessionCookie);

        HttpResponse response = httpClient.execute(httpPost, context);
        HttpEntity resEntity = response.getEntity();  
        String Response = "";
        if (response != null) 
        {    
            Response = EntityUtils.toString(resEntity); 
        }
        return Response;
    } 
    catch (IOException e) 
    {
        e.printStackTrace();
    }

    return "Exception";
}

答案 2 :(得分:0)

这正是你想要的。

您可以通过GET或POST发送JSON对象

<强> HttpRequestWithEntity.java

import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;

public class HttpRequestWithEntity extends HttpEntityEnclosingRequestBase {

    private String method;

    public HttpRequestWithEntity(String url, String method) {
        if (method == null || (method != null && method.isEmpty())) {
            this.method = HttpMethod.GET;
        } else {
            this.method = method;
        }
        try {
            setURI(new URI(url));
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getMethod() {
        return this.method;
    }

}

如何使用???

我为POST&amp;编写了方法 sendJSONObject 。 SET

/**
 * 
 * @param url stands for API
 * @param 
 *      params[i][0] stands for column's name
 *      params[i][1] stands for value which respective with column's name
 * @return InputStream which got from Server
 */
public static int sendJSONObject(IGetUserData iUserId, String method, String url, String[]... params) {
    InputStream mInputStream = null;
    HttpClient mHttpClient = null;
    HttpRequestWithEntity mHttpGet = null;
    int status = Def.REQUEST_INVALID;
    try {
        mHttpClient = new DefaultHttpClient();

        mHttpGet = new HttpRequestWithEntity(url, method);

        JSONObject mObject = new JSONObject();
        for (String[] pair : params) {
            mObject.put(pair[0], pair[1]);
        }

        StringEntity mStringEntity = new StringEntity(mObject.toString());
        mStringEntity.setContentEncoding("UTF-8");
        mStringEntity.setContentType("application/json");

        mHttpGet.setEntity(mStringEntity);          
        HttpResponse mResponse = mHttpClient.execute(mHttpGet);
        status = mResponse.getStatusLine().getStatusCode();

        Log.d(TAG, "status: " + status);
        if (mResponse != null && 
                (status == Def.CREATED || status == Def.OK)) {
            mInputStream = mResponse.getEntity().getContent();  
            if(mInputStream != null){
                String json = StreamUtils.converStreamToString(mInputStream);
                userId = JSONUtils.getUserId(json);
                iUserId.sendUserId(userId);
                Log.d("viet","userid = " + userId);
            }
        }

    } catch (Exception e) {
        Log.e(TAG, "Error during send");
        status = Def.NETWORK_ERROR;
    }
    return status;
}

这种方式对我来说是正确的

如果您想要上传照片或视频,可以在此处显示进度条。

public static class UploadPhoto extends AsyncTask<String, Void, InputStream> {
    private static final String TAG = "UploadImage";
    byte[] buffer;
    byte[] data;
    //private long dataLength = 0;
    private INotifyProgressBar iNotifyProgressBar;
    private int user_id;
    private IAddNewItemOnGridView mAddNewItemOnGridView;
    public UploadPhoto(INotifyProgressBar iNotifyProgressBar, 
            IAddNewItemOnGridView mAddNewItemOnGridView, int user_id) {
        this.iNotifyProgressBar = iNotifyProgressBar;
        this.user_id = user_id;
        this.mAddNewItemOnGridView = mAddNewItemOnGridView;
    }

    @Override
    protected InputStream doInBackground(String... names) {
        File mFile = null;
        FileBody mBody = null;
        File dcimDir = null;
        try {
            String fileName = names[0];
            dcimDir = Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
            mFile = new File(dcimDir, Def.PHOTO_TEMP_DIR + fileName);
            if (!mFile.isFile()) {
                iNotifyProgressBar.notify(0, UploadStatus.FAILED);
                return null;
            }
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost postRequest = new HttpPost(Def.BASE_URL 
                    + String.format("/%d/list", this.user_id));
            final int maxBufferSize = 10 * 1024;
            mBody = new FileBody(mFile, fileName, "image/jpeg", "UTF-8"){
                int bytesRead, bytesAvailable, bufferSize;
                InputStream mInputStream = super.getInputStream();
                int dataLength = mInputStream.available();
                @Override
                public void writeTo(OutputStream out) throws IOException {
                    bytesAvailable = mInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    buffer = new byte[bufferSize];
                    bytesRead = mInputStream.read(buffer, 0, bufferSize);
                    while (bytesRead > 0) {
                        out.write(buffer, 0, bufferSize);
                        bytesAvailable = mInputStream.available();
                        bufferSize = Math.min(bytesAvailable, maxBufferSize);
                        bytesRead = mInputStream.read(buffer, 0, bufferSize);
                        int progress = (int) (100 - ((bytesAvailable * 1.0) / dataLength) * 100);
                        Log.d(TAG, "Result: " + progress + "%");
                        if (progress == 100) {
                            iNotifyProgressBar.notify(progress, UploadStatus.SUCCESS);
                        } else {
                            iNotifyProgressBar.notify(progress, UploadStatus.UPLOADING);
                        }
                    }
                }
                @Override
                protected void finalize() throws Throwable {
                    super.finalize();
                    if (mInputStream != null) {
                        mInputStream.close();
                    }
                }   
            };

            MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);              
            reqEntity.addPart("photo", mBody);
            postRequest.setEntity(reqEntity);
            HttpResponse response = httpClient.execute(postRequest);
            InputStream mInputStream = response.getEntity().getContent();
            return mInputStream == null ? null : mInputStream;
        } catch (IOException e) {
            Log.e(TAG, "Error causes during upload image: " + e.getMessage());
            e.printStackTrace();
            iNotifyProgressBar.notify(0, UploadStatus.FAILED);
        } finally {
            Log.v(TAG, "Close file");
            if (mFile != null) {
                mFile = null;
            }
            if (mBody != null) {
                mBody = null;
            }
            if (dcimDir != null) {
                dcimDir = null;
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(InputStream result) {
        if (result == null) {
            iNotifyProgressBar.notify(0, UploadStatus.FAILED);
        } else {
            PhotoInfo mPhotoInfo = ApiUtils.convertStreamToPhotoInfo(result);
            if (mAddNewItemOnGridView != null && mPhotoInfo != null) {
                mAddNewItemOnGridView.notifyAdded(mPhotoInfo);
                Log.d(TAG, "Upload completed!!");
            } else {
                Log.d(TAG, "Upload is failed!!");
                iNotifyProgressBar.notify(0, UploadStatus.FAILED);
            }
        }
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
}