Java Android中的HttpPost图像

Java Android中的HttpPost图像,java,android,http-post,image-uploading,Java,Android,Http Post,Image Uploading,我正在尝试对URL进行HTTP发布 我按照回答中的代码进行操作: http://stackoverflow.com/questions/2935946/sending-images-using-http-post 所有HttpComponent库都已成功包含到我的项目中 但是,在手机上测试代码时,我遇到此错误: 01-09 10:27:53.773: E/AndroidRuntime(4473): FATAL EXCEPTION: main 01-09 10:27:53.773: E/Andr

我正在尝试对URL进行HTTP发布

我按照回答中的代码进行操作:

http://stackoverflow.com/questions/2935946/sending-images-using-http-post
所有HttpComponent库都已成功包含到我的项目中

但是,在手机上测试代码时,我遇到此错误:

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)
01-09 10:27:53.773:E/AndroidRuntime(4473):致命异常: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):位于org.apache.http.entity.mime.content.FileBody.(FileBody.java:85)
01-09 10:27:53.773:E/AndroidRuntime(4473):位于com.geliesmedia.thumbqoo.services.HttpContentPost.sendPost(HttpContentPost.java:36)
01-09 10:27:53.773:E/AndroidRuntime(4473):在com.geliesmedia.thumbqoo.ProductPublishActivity$4.onClick(ProductPublishActivity.java:224)
01-09 10:27:53.773:E/AndroidRuntime(4473):在android.view.view.performClick(view.java:4204)
01-09 10:27:53.773:E/AndroidRuntime(4473):在android.view.view$PerformClick.run(view.java:17355)
01-09 10:27:53.773:E/AndroidRuntime(4473):位于android.os.Handler.handleCallback(Handler.java:725)
01-09 10:27:53.773:E/AndroidRuntime(4473):位于android.os.Handler.dispatchMessage(Handler.java:92)
01-09 10:27:53.773:E/AndroidRuntime(4473):在android.os.Looper.loop(Looper.java:137)
01-09 10:27:53.773:E/AndroidRuntime(4473):位于android.app.ActivityThread.main(ActivityThread.java:5041)
01-09 10:27:53.773:E/AndroidRuntime(4473):位于java.lang.reflect.Method.Invokenactive(本机方法)
01-09 10:27:53.773:E/AndroidRuntime(4473):位于java.lang.reflect.Method.invoke(Method.java:511)
01-09 10:27:53.773:E/AndroidRuntime(4473):在com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-09 10:27:53.773:E/AndroidRuntime(4473):位于com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-09 10:27:53.773:E/AndroidRuntime(4473):在dalvik.system.NativeStart.main(本机方法)
这是我的代码:

@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);

        }
    }
}
@SuppressWarnings(“弃用”)
公共类HttpContentPost{
私有静态最终字符串BASE_URL=”http://example.com/api/index.php";
公共静态void sendPost(字符串imagePath,ProductRaw数据)
抛出IOException,ClientProtocolException{
字符串响应体;
HttpClient=new DefaultHttpClient();
HttpPost请求=新的HttpPost(基本URL);
多方实体=新多方实体(
HttpMultipartMode.BROWSER_兼容);
文件文件=新文件(imagePath);
ContentBody encFile=newfilebody(文件“image/jpg”);
Log.i(“标记”,“构建HTTP实体”);
entity.addPart(“文件”,encFile);
实体。添加部分(“行动”,新的StringBody(“publishMarket”);
entity.addPart(“电子邮件”,新的StringBody(data.ownerEmail));
entity.addPart(“密码”,新的StringBody(data.ownerPasswd));
entity.addPart(“标题”,新的StringBody(data.productName));
entity.addPart(“description”,新的StringBody(data.productDesc));
entity.addPart(“货币代码”,新的StringBody(data.productCurrency));
entity.addPart(“price”,新的StringBody(data.productPrice));
entity.addPart(“category”,新的StringBody(data.productCat));
entity.addPart(“tag”,新的StringBody(data.productTag));
请求。设置实体(实体);
Log.i(“TAG”,request.toString());
ResponseHandler ResponseHandler=新BasicResponseHandler();
responseBody=client.execute(请求、响应句柄);
if(responseBody!=null&&responseBody.length()>0){
Log.w(“标签”,“响应图像上传”+响应库);
}
}
}

有人知道如何解决此问题吗?

p请检查以下代码:

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

我最后做了以下几件事:

  • 删除所需的库(项目属性>库选项卡>删除所述*jar)
  • 从项目的我的libs目录中删除所需的*jar
  • 清理我的项目
  • 重新启动Eclipse

  • 重新添加必需的*jar(项目属性>库选项卡>添加外部jar

  • (奇怪的是)从order和Export选项卡更改所述JAR的顺序(我将JAR顺序放在我项目的src+gen文件夹之后)
  • 再次做一次清洁
  • 运行应用程序
  • 然而,我无法解释这些步骤的原因。我只是在这里通读了这个问题中提供的所有(并尝试了所有)解决方案


    希望这能在将来对您有所帮助。

    实际上我知道这是因为它找不到所需的类名。我不明白的是为什么?因为据我所知,我已经导入了所有必需的*jar。您是否将httpcore-x.x.jar添加到构建路径中了?是的。顺便说一句……我遇到了这个问题,目前正在测试每一个sugge我忽略了异常发生在运行时而不是编译时。我会检查以确保在上传代码时正确导出JAR。