3

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.

4
  • stackoverflow.com/questions/6218143/… Commented Aug 5, 2013 at 4:21
  • my question is how I'm going to send files in JSON not only text... Commented Aug 5, 2013 at 4:37
  • oops i m sorry, not sure since didnt used yet but try this in case it helps : codeproject.com/Questions/464629/… Commented Aug 5, 2013 at 4:45
  • Well, JSON is text so you don't need to do anything special with it. But you might want to see this for an approach to sending JSON plus other data: stackoverflow.com/questions/3938569/… Commented Aug 5, 2013 at 4:57

3 Answers 3

9

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("[email protected]"));
        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.

Sign up to request clarification or add additional context in comments.

4 Comments

the FIle Body class and the MultipartEntity class is not working I can import it what should I do?
You need to add these jar files in your lib directory . httpmime-4.1.2.jar and ksoap2-android-assembly-2.5.8-jar-with-dependencies.jar
what if I want to send not only image I mean how about I want to send non media files does it work?
you can download httpmime-4.1.2.jar from below URL. grepcode.com/snapshot/repo1.maven.org/maven2/… and ksoap2-android-assembly-2.5.8-jar-with-dependencies.jar on the Link generalfiles.org/go/127009346600
4

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

2 Comments

oh really so I don't need it to convert in any format for able to send on json?
I've found MultiPartEntity will send the JSON as a string.
0

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

1 Comment

:) I know. If you want to send Image or Video, Please looking for below answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.