OkHttp使用表单数据上传PDF和PNG

时间:2016-03-16 06:26:37

标签: android multipartform-data okhttp stetho

我有一个应用程序,它会将PDF和PNG图像文件以及其他一些数据上传到服务器。我使用Stetho作为检查员,但每次我尝试打开日志时,它都会挂起然后崩溃,所以我不知道我发送到服务器的是否正确。

以下是所需数​​据(方法:POST,内容类型:multipart / form-data):

  • 内容处理:表单数据 命名=" SRCFILE" Content-Type:application / pdf(要上传的PDF文件)
  • 内容 - 处置:表单数据; 命名=" SignFile" Content-Type:image / png(要上传的PNG文件)
  • 模式(字符串值)
  • Req(字符串值)
  • 令牌(字符串值)

这是我第一次这样做,但根据我的研究,这是我上传所述数据的代码:

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 上传工作,现在开始下载响应。

1 个答案:

答案 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";
    }
});