I am trying to upload a picture to the server using POST using multipart / form-data . For me it turned out to be harder than I thought. Here is an example of what I need to send from the application.
----WebKitFormBoundaryE19zNvXGzXaLvS5C Content-Disposition: form-data; name="image"; filename="imageName.jpeg" Content-Type: image/jpeg ----WebKitFormBoundaryE19zNvXGzXaLvS5C Below I tried to implement this, but the server gives me an error when using this code:
public static String executeHttpLoadImage(String url, String nameValueF, String paramValueF, String nameValueS, String paramValueS, String filePath, String fileName) throws Exception { BufferedReader in = null; try { HttpClient client = createHttpClient(); HttpPost request = new HttpPost(); //post request.setURI(new URI(url)); request.setHeader("Content-Type", "multipart/form-data"); //set header request.setHeader(nameValueF, paramValueF); //set header request.setHeader(nameValueS, paramValueS); //set header //set multipart MultipartEntity mpEntity = new MultipartEntity(); //multipart File file = new File(filePath); //file path ContentBody cbFile = new FileBody(file, "image/jpeg"); //body mpEntity.addPart(fileName, cbFile); //add request.setEntity(mpEntity); //set multipart HttpResponse response = client.execute(request); in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL); } in.close(); String result = sb.toString(); return result; } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } }