-1

I am trying to do an HTTP Post to a URL.

I followed the code from this answer:

http://stackoverflow.com/questions/2935946/sending-images-using-http-post

All HttpComponent libraries has been successfully included to my project.

However i am getting this error when testing the code on the phone:

01-09 10:27:53.773: E/AndroidRuntime(4473): FATAL EXCEPTION: main
01-09 10:27:53.773: E/AndroidRuntime(4473): java.lang.NoClassDefFoundError: org.apache.http.entity.ContentType
01-09 10:27:53.773: E/AndroidRuntime(4473):     at org.apache.http.entity.mime.content.FileBody.<init>(FileBody.java:85)
01-09 10:27:53.773: E/AndroidRuntime(4473):     at com.gelliesmedia.thumbqoo.services.HttpContentPost.sendPost(HttpContentPost.java:36)
01-09 10:27:53.773: E/AndroidRuntime(4473):     at com.gelliesmedia.thumbqoo.ProductPublishActivity$4.onClick(ProductPublishActivity.java:224)
01-09 10:27:53.773: E/AndroidRuntime(4473):     at android.view.View.performClick(View.java:4204)
01-09 10:27:53.773: E/AndroidRuntime(4473):     at android.view.View$PerformClick.run(View.java:17355)
01-09 10:27:53.773: E/AndroidRuntime(4473):     at android.os.Handler.handleCallback(Handler.java:725)
01-09 10:27:53.773: E/AndroidRuntime(4473):     at android.os.Handler.dispatchMessage(Handler.java:92)
01-09 10:27:53.773: E/AndroidRuntime(4473):     at android.os.Looper.loop(Looper.java:137)
01-09 10:27:53.773: E/AndroidRuntime(4473):     at android.app.ActivityThread.main(ActivityThread.java:5041)
01-09 10:27:53.773: E/AndroidRuntime(4473):     at java.lang.reflect.Method.invokeNative(Native Method)
01-09 10:27:53.773: E/AndroidRuntime(4473):     at java.lang.reflect.Method.invoke(Method.java:511)
01-09 10:27:53.773: E/AndroidRuntime(4473):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-09 10:27:53.773: E/AndroidRuntime(4473):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-09 10:27:53.773: E/AndroidRuntime(4473):     at dalvik.system.NativeStart.main(Native Method)

This is my Code:

@SuppressWarnings("deprecation")
public class HttpContentPost {
    private static final String BASE_URL = "http://example.com/api/index.php";
    public static void sendPost(String imagePath, ProductRaw data)
            throws IOException, ClientProtocolException {

        String responseBody;
        HttpClient client = new DefaultHttpClient();
        HttpPost request = new HttpPost(BASE_URL);

        MultipartEntity entity = new MultipartEntity(
                HttpMultipartMode.BROWSER_COMPATIBLE);

        File file = new File(imagePath);
        ContentBody encFile = new FileBody(file,"image/jpg");

        Log.i("TAG", "BUILDING HTTP ENTITY");
        entity.addPart("file", encFile);
        entity.addPart("action", new StringBody("publishMarket"));
        entity.addPart("email", new StringBody(data.ownerEmail));
        entity.addPart("password", new StringBody(data.ownerPasswd));
        entity.addPart("title", new StringBody(data.productName));
        entity.addPart("description", new StringBody(data.productDesc));
        entity.addPart("currency_code", new StringBody(data.productCurrency));
        entity.addPart("price", new StringBody(data.productPrice));
        entity.addPart("category", new StringBody(data.productCat));
        entity.addPart("tag", new StringBody(data.productTag));

        request.setEntity(entity);
        Log.i("TAG", request.toString());

        ResponseHandler<String> responsehandler = new BasicResponseHandler();
        responseBody = client.execute(request, responsehandler);

        if (responseBody != null && responseBody.length() > 0) {
            Log.w("TAG", "Response image upload" + responseBody);

        }
    }
}

Does anyone know how can i solve this?

Jeremy
  • 2,516
  • 8
  • 46
  • 80
  • http://stackoverflow.com/search?q=java.lang.NoClassDefFoundError – Brian Roach Jan 09 '14 at 03:37
  • Actually i am aware that it is because it cannot locate the required classname. What i don't understand is why? Because as far as i know i have import all the required *jar – Jeremy Jan 09 '14 at 03:43
  • Did you add httpcore-x.x.jar to the build path? – blackcompe Jan 09 '14 at 04:04
  • Yup. Btw... I came across to this question, and currently testing every single suggestion there. – Jeremy Jan 09 '14 at 04:12
  • I overlooked that the exception occurred during runtime and not at compile-time. I'd check to make sure the JARs are being exported correctly when you upload the code. – blackcompe Jan 09 '14 at 04:30
  • @blackcompe Yup, i finally found the solution after reading through that other question. – Jeremy Jan 09 '14 at 04:35

2 Answers2

0

Pplease check following code :

public  int upLoad2Server(String sourceFileUri) throws JSONException, IOException,MalformedURLException,FileNotFoundException {
    /**
     * create json object and pass into the webservice basic parameter
     */
    jsonObjAuth=new JSONObject();
    /*try {*/
        jsonObjAuth.put("image", sourceFileUri);
        jsonObjAuth.put("user", UserInfo.username);
        jsonObjAuth.put("pass", UserInfo.userpass);
        jsonObjAuth.put("user_id", UserInfo.user_id);
        jsonObjAuth.put("patientid", UserInfo.user_id);
        jsonObjAuth.put("type", imgtype);
        jsonObjAuth.put("pdid", pdid);
    /*} catch (JSONException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }*/

    //webservice uri
    String upLoadServerUri =URLS.WS_BASE_URL+URLS.WS_ADD_IMAGE;

    // String [] string = sourceFileUri;
    String fileName = sourceFileUri;

    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    DataInputStream inStream = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    String responseFromServer = "";

    File sourceFile = new File(sourceFileUri);
    if (!sourceFile.isFile()) {
        Log.e("Huzza", "Source File Does not exist");
        return 0;
    }
    /*try {*/
        FileInputStream fileInputStream = new FileInputStream(sourceFile);
        URL url = new URL(upLoadServerUri);
        conn = (HttpURLConnection) url.openConnection(); // Open a HTTP
                                                            // connection to
                                                            // the URL
        Log.i("URL_new","conn="+url+"="+conn);
        conn.setDoInput(true); // Allow Inputs
        conn.setDoOutput(true); // Allow Outputs
        conn.setUseCaches(false); // Don't use a Cached Copy
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type",
                "multipart/form-data;boundary=" + boundary);
        // "Content-Disposition: form-data; name=\"image";
        // filename=\"TypeA.png"\r\n"
        // String
        Log.i("data", "json " + jsonObjAuth.toString());
        //conn.setRequestProperty("data", jsonObjAuth.toString());
        dos = new DataOutputStream(conn.getOutputStream());
        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"image\";filename=\""
                + imgtype + "\"" + lineEnd);

        Log.i("imgtype","filename:"+imgtype);
        dos.writeBytes(lineEnd);
        bytesAvailable = fileInputStream.available(); // create a buffer of
                                                        // maximum size
        Log.i("Huzza", "Initial .available : " + bytesAvailable);
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];
        // read file and write it into form...
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);

        while (bytesRead > 0) {
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        // send multipart form data necesssary after file data...
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + lineEnd);
        String json= jsonObjAuth.toString();
        dos.writeBytes("Content-Disposition: form-data; name=\"data\"\r\n\r\n" + json + "\r\n");            
        //[myReturn appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n%@\r\n",[formKeys objectAtIndex:i],[myDictionary valueForKey:[formKeys objectAtIndex:i]]] dataUsingEncoding:NSASCIIStringEncoding]];
        ///////

        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        // Responses from the server (code and message)
        //serverResponseCode = conn.getResponseCode();
        //String serverResponseMessage = conn.getResponseMessage();
        // close streams
        Log.i("Upload file to server", fileName + " File is written");
        /*Log.i("Upload file to server", "HTTP Response is : "
                + serverResponseMessage + ": " + serverResponseCode);*/
        fileInputStream.close();
        dos.flush();
        dos.close();
    // this block will give the response of upload link
    /*try {*/
        BufferedReader rd = new BufferedReader(new InputStreamReader(
                conn.getInputStream()));

        while ((line = rd.readLine()) != null) {
            Log.i("Huzza", "RES Message: " + line);
        }
        rd.close();
    /*} catch (IOException ioex) {
        Log.e("Huzza", "error: " + ioex.getMessage(), ioex);
    }*/
    return serverResponseCode; // like 200 (Ok)

} // end upLoad2Server
Kitkat
  • 77
  • 16
dipali
  • 10,966
  • 5
  • 25
  • 51
0

I ended up doing the following:

  1. Remove the required libraries (Project properties > Library tabs > remove said *jars
  2. Remove the required *jars from my libs directory of my Project
  3. Clean my project
  4. Restart Eclipse

  5. re-add required *jars (Project properties > Library tabs > Add External JARs

  6. (weirdly enough) Change the order of the said JARs from the Order and Export tabs (i put the jars order immediately after the src + gen folders of my Projects.
  7. once again do a Clean
  8. Run the apps..

I however cannot explain why these steps. I just read through all (and tried all) the solution provided in this question here NoClassDefFoundError - Eclipse and Android

Hope this could help you in the future.

Community
  • 1
  • 1
Jeremy
  • 2,516
  • 8
  • 46
  • 80