I have an app which will upload a PDF and PNG image file to the server, along with some other data. I'm using Stetho as inspector but everytime I try to open the log, it hangs and then crashes, so I have no idea if what I'm sending to the server is right.
Here are the required data (Method: POST, Content-Type: multipart/form-data):
- Content-Disposition: form-data name="SrcFile" Content-Type: application/pdf (The PDF File to upload)
- Content-Disposition: form-data; name="SignFile" Content-Type: image/png (The PNG File to upload)
- Mode (String value)
- Req (String value)
- Token (String value)
This is my first to do this but based from my research, here is my code to upload said data:
final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
}
};
// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
OkHttpClient client = new OkHttpClient();
client.setSslSocketFactory(sslContext.getSocketFactory());
client.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
client.networkInterceptors().add(new StethoInterceptor());
File pngFile = new File(Environment.getExternalStorageDirectory() + "signature_" + pdfFile.getFileName() + ".png");
File pdf = new File(Environment.getExternalStorageDirectory() + pdfFile.getFileName());
String mode = "SampleMode"
Headers headers = new Headers.Builder()
.add("Content-Type", "multipart/form-data")
.build();
MultipartBuilder multipartBuilder = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addFormDataPart("Req", "SampleRequest")
.addFormDataPart("Token", "MyAPIToken")
.addFormDataPart("Mode", mode)
.addFormDataPart("SrcFile", pdf.getAbsolutePath(), RequestBody.create(MediaType.parse("application/pdf"), pdf))
.addFormDataPart("SignFile", pngFile.getAbsolutePath(), RequestBody.create(MediaType.parse("image/png"), pngFile));
RequestBody requestBody = multipartBuilder
.build();
Request request = new Request.Builder()
.url("MyURLHere")
.headers(headers)
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
I just would like to know if I'm doing the upload correctly, or maybe I set some parameters wrong. Again, I can't seem to use Stetho coz it hangs whenever I try to open it. Thanks!
Edited Turns out I just switched SrcFile and SignFile! XD The upload works, now on to downloading the response.