简体   繁体   English

如何在Android中运行cUrl调用?

[英]How can I run cUrl calls in Android?

I Specifically need to do file upload via cURL in Android(noob). 我特别需要在Android(noob)中通过cURL进行文件上传。 For Something like curl -F "file=@temp.txt" https://server.com . 对于诸如curl -F "file=@temp.txt" https://server.com

Can i get the alternative an snippet in java? 我可以在Java中获取替代代码段吗?

While it is possible to run that command directly from Java, you should not do that. 尽管可以直接从Java运行该命令,但是您不应这样做。 Each phone is different and it is very much possible that some Android phones might not have curl installed on them. 每部手机都不一样,某些Android手机很有可能没有安装curl功能。

You can use libraries such as Apache or OkHttp to do so. 您可以使用Apache或OkHttp之类的库来这样做。 Here is a snippet that works with OkHttp 3.2.0: 这是与OkHttp 3.2.0兼容的代码段:

//file is your opened file and url is the server url
OkHttpClient client = new OkHttpClient.Builder().build();
RequestBody formBody = new MultipartBody.Builder()
    .setType(MultipartBody.FORM)
    .addFormDataPart("file", file.getName(),
        RequestBody.create(MediaType.parse("text/plain"), file))
    .build();
Request request = new Request.Builder().url(url).post(formBody).build();
Response response = client.newCall(request).execute();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM