我有一个应用程序,它会将PDF和PNG图像文件以及其他一些数据上传到服务器。我使用Stetho作为检查员,但每次我尝试打开日志时,它都会挂起然后崩溃,所以我不知道我发送到服务器的是否正确。
以下是所需数据(方法:POST,内容类型:multipart / form-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();
我只是想知道我是否正确上传,或者我设置了一些参数错误。再一次,我似乎无法使用Stetho因为每当我尝试打开它时它就会挂起。谢谢!
被修改 事实证明我刚刚切换了SrcFile和SignFile! XD 上传工作,现在开始下载响应。
答案 0 :(得分:0)
我建议您使用此jar。
使用此库
SyncHttpClient client = new SyncHttpClient();
RequestParams param = new RequestParams();
param.put("email", email);
param.put("title", title);
try {
if (!path.equals("") || path != null) {
param.put("logo", new File(path));
} else {
path = " ";
param.put("logo", new File(path));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String link = "your link";
client.post(link, param, new TextHttpResponseHandler() {
@Override
public void onSuccess(int arg0, Header[] arg1, String arg2) {
success1 = "true";
}
@Override
public void onFailure(int arg0, Header[] arg1, String arg2,
Throwable arg3) {
success1 = "false";
}
});