Android中的HttpPost图片

时间:2014-01-09 03:31:34

标签: java android http-post image-uploading

我正在尝试对网址进行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)

这是我的代码:

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

        }
    }
}

有谁知道我怎么解决这个问题?

2 个答案:

答案 0 :(得分:0)

请检查以下代码:

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

答案 1 :(得分:0)

我最终做了以下事情:

  1. 删除所需的库(项目属性&gt;库标签&gt;删除所述* jars
  2. 从我的项目的libs目录中删除所需的* jars
  3. 清理我的项目
  4. 重启Eclipse

  5. 重新添加必需的* jars(项目属性&gt;库标签&gt;添加外部JAR

  6. (奇怪的是)从Order和Export选项卡更改所述JAR的顺序(我将jars顺序放在我的Projects的src + gen文件夹之后。
  7. 再次做一个清洁
  8. 运行应用..
  9. 然而,我无法解释为什么这些步骤。我只是通过这里NoClassDefFoundError - Eclipse and Android

    阅读了这个问题中提供的所有解决方案(并尝试了所有解决方案)

    希望这可以在将来帮助你。