android httpurlconnection post multipart 2fform data

Solutions on MaxInterview for android httpurlconnection post multipart 2fform data by the best coders in the world

showing results for - "android httpurlconnection post multipart 2fform data"
Yuna
19 Jun 2017
1public class MultipartUtility {
2    private final String boundary;
3    private static final String LINE_FEED = "\r\n";
4    private HttpURLConnection httpConn;
5    private String charset;
6    private OutputStream outputStream;
7    private PrintWriter writer;
8
9    /**
10     * This constructor initializes a new HTTP POST request with content type
11     * is set to multipart/form-data
12     *
13     * @param requestURL
14     * @param charset
15     * @throws IOException
16     */
17    public MultipartUtility(String requestURL, String charset)
18            throws IOException {
19        this.charset = charset;
20
21        // creates a unique boundary based on time stamp
22        boundary = "===" + System.currentTimeMillis() + "===";
23        URL url = new URL(requestURL);
24        httpConn = (HttpURLConnection) url.openConnection();
25        httpConn.setUseCaches(false);
26        httpConn.setDoOutput(true);    // indicates POST method
27        httpConn.setDoInput(true);
28        httpConn.setRequestProperty("Content-Type",
29                "multipart/form-data; boundary=" + boundary);
30        outputStream = httpConn.getOutputStream();
31        writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
32                true);
33    }
34
35    /**
36     * Adds a form field to the request
37     *
38     * @param name  field name
39     * @param value field value
40     */
41    public void addFormField(String name, String value) {
42        writer.append("--" + boundary).append(LINE_FEED);
43        writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
44                .append(LINE_FEED);
45        writer.append("Content-Type: text/plain; charset=" + charset).append(
46                LINE_FEED);
47        writer.append(LINE_FEED);
48        writer.append(value).append(LINE_FEED);
49        writer.flush();
50    }
51
52    /**
53     * Adds a upload file section to the request
54     *
55     * @param fieldName  name attribute in <input type="file" name="..." />
56     * @param uploadFile a File to be uploaded
57     * @throws IOException
58     */
59    public void addFilePart(String fieldName, File uploadFile)
60            throws IOException {
61        String fileName = uploadFile.getName();
62        writer.append("--" + boundary).append(LINE_FEED);
63        writer.append(
64                "Content-Disposition: form-data; name=\"" + fieldName
65                        + "\"; filename=\"" + fileName + "\"")
66                .append(LINE_FEED);
67        writer.append(
68                "Content-Type: "
69                        + URLConnection.guessContentTypeFromName(fileName))
70                .append(LINE_FEED);
71        writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
72        writer.append(LINE_FEED);
73        writer.flush();
74
75        FileInputStream inputStream = new FileInputStream(uploadFile);
76        byte[] buffer = new byte[4096];
77        int bytesRead = -1;
78        while ((bytesRead = inputStream.read(buffer)) != -1) {
79            outputStream.write(buffer, 0, bytesRead);
80        }
81        outputStream.flush();
82        inputStream.close();
83        writer.append(LINE_FEED);
84        writer.flush();
85    }
86
87    /**
88     * Adds a header field to the request.
89     *
90     * @param name  - name of the header field
91     * @param value - value of the header field
92     */
93    public void addHeaderField(String name, String value) {
94        writer.append(name + ": " + value).append(LINE_FEED);
95        writer.flush();
96    }
97
98    /**
99     * Completes the request and receives response from the server.
100     *
101     * @return a list of Strings as response in case the server returned
102     * status OK, otherwise an exception is thrown.
103     * @throws IOException
104     */
105    public List<String> finish() throws IOException {
106        List<String> response = new ArrayList<String>();
107        writer.append(LINE_FEED).flush();
108        writer.append("--" + boundary + "--").append(LINE_FEED);
109        writer.close();
110
111        // checks server's status code first
112        int status = httpConn.getResponseCode();
113        if (status == HttpURLConnection.HTTP_OK) {
114            BufferedReader reader = new BufferedReader(new InputStreamReader(
115                    httpConn.getInputStream()));
116            String line = null;
117            while ((line = reader.readLine()) != null) {
118                response.add(line);
119            }
120            reader.close();
121            httpConn.disconnect();
122        } else {
123            throw new IOException("Server returned non-OK status: " + status);
124        }
125        return response;
126    }
127}
128
Fallon
12 Oct 2019
1    MultipartUtility multipart = new MultipartUtility(requestURL, charset);
2
3    // In your case you are not adding form data so ignore this
4                /*This is to add parameter values */
5                for (int i = 0; i < myFormDataArray.size(); i++) {
6                    multipart.addFormField(myFormDataArray.get(i).getParamName(),
7                            myFormDataArray.get(i).getParamValue());
8                }
9
10
11//add your file here.
12                /*This is to add file content*/
13                for (int i = 0; i < myFileArray.size(); i++) {
14                    multipart.addFilePart(myFileArray.getParamName(),
15                            new File(myFileArray.getFileName()));
16                }
17
18                List<String> response = multipart.finish();
19                Debug.e(TAG, "SERVER REPLIED:");
20                for (String line : response) {
21                    Debug.e(TAG, "Upload Files Response:::" + line);
22// get your server response here.
23                    responseString = line;
24                }
25