doInBackground()中的错误 - > NoClassDefFoundError:org.apache.http.entity.ContentType

时间:2015-03-09 05:30:37

标签: java android apache android-asynctask

我正在将图片上传到服务器。我{.1}}中存在一些错误.addpart with fileupload。我是新手,所以请帮助我。 根据我的说法,变量filepath在Asynctask中有一些问题。 我的Asynctask文件具有所需的权限。

manifest.xml

错误日志:

public class UploadActivity extends Activity{
private String filePath = null;
private Button btnUpload;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_upload);
    btnUpload = (Button) findViewById(R.id.btnUpload);
    // Receiving the data from previous activity
    Intent i = getIntent();

    // image or video path that is captured in previous activity
    filePath = i.getStringExtra("filePath");

    btnUpload.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // uploading the file to server
            new Upload().execute();
        }
    });
}
/**
 * Uploading the file to server
 * */
private class Upload extends AsyncTask<Void, Integer, String> {
    @Override
    protected String doInBackground(Void... params) {
        return uploadFile();
    }

    @SuppressWarnings("deprecation")
    private String uploadFile() {
        String responseString = null;
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://192.168.1.102/fileUpload.php");

           MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
           File sourceFile = new File(filePath);
            // Adding file data to http body
            entity.addPart("image", new FileBody(sourceFile));
            totalSize = entity.getContentLength();
            httppost.setEntity(entity);

            // Making server call
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity r_entity = response.getEntity();

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                // Server response
                responseString = EntityUtils.toString(r_entity);
            } else {
                responseString = "Error occurred! Http Status Code: "
                        + statusCode;
            }
        } catch (ClientProtocolException e) {
            responseString = e.toString();
        } catch (IOException e) {
            responseString = e.toString();
        }
        return responseString;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
    }
}  
}

2 个答案:

答案 0 :(得分:1)

您的问题很可能是您没有正确导入org.apache.http库。这就是为什么你的崩溃给你java.lang.NoClassDefFoundError

您需要做的是确保正确导入库。因此,如果您使用Eclipse,请从此link

下载JAR文件

如果您使用的是Android Studio,请确保Gradle

中的{{1}}文件中的相关性

另请查看此link,它会讨论与您类似的问题

答案 1 :(得分:0)

添加包含org.apache.http.entity.ContentType的库以构建路径。