Question

I want to send files in JSON using http client I don't know how would I start can anyone suggest what should I need to do? I'm going to send data on this JSON format:

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

As you see I'm going to send files in chunk. I don't know if I'm going to convert the file into byte array. If I needed can anyone give some sample code thanks.

Was it helpful?

Solution

To send Text File or Image File on Server you can use 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());
      }

This is working, as this code is part of my Running project.

OTHER TIPS

You can send Text file And media file using 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";
}

Here is exactly what you want.

You can send JSON Object by GET or POST

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;
    }

}

How to use???

I wrote method sendJSONObject for both POST & 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;
}

This way work correcty with me

And here if you want to upload photo or video and you can show progressbar if you want.

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();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top