精华内容
下载资源
问答
  • OkHttpClient 上传文件

    千次阅读 2017-11-29 14:29:26
    OkHttpClient okHttpClient=new OkHttpClient(); MediaType parse = MediaType.parse("text/x-markdown;charset=utf-8"); File file = new File(Environment.getExternalStorageDirectory(),"note01.md"); Request b
    OkHttpClient okHttpClient=new OkHttpClient();
    MediaType parse = MediaType.parse("text/x-markdown;charset=utf-8");
    File file = new File(Environment.getExternalStorageDirectory(),"note01.md");
    Request builder=new Request.Builder()
            .post(RequestBody.create(parse,file))
            .url("https://api.github.com/markdown/raw")
            .build();
    Call call = okHttpClient.newCall(builder);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
    
        }
    
        @Override
        public void onResponse(Call call, Response response) throws IOException {
            Log.d("=======1111",response.body().string());
        }
    });
    展开全文
  • } } private CompareInfo compareRquest(File file, File file2) throws Exception { OkHttpClient httpClient = new OkHttpClient(); String sessionId = ""; //先登录 获取sessionId ,post json方式 Map,Object>...
    @PostMapping(value="/api/candidate/compare")
        public JsonResponse<String> compare(MultipartFile file, String idCard) throws Exception {
            JsonResponse<String> result = candidateService.compare(file,idCard);
            return result;
        }
    
    public JsonResponse<String> compare(MultipartFile sourceFile, String idCard) throws Exception {
            Map<String, Object> params = new HashMap();
            params.put("idCard",idCard);
            Candidate candidate = candidateDao.getByParams(params);
            if(candidate!=null && candidate.getHeadUrl()!=null){
                String path = candidate.getHeadUrl();
                File head = new File(path);
                File f = new File(sourceFile.getOriginalFilename());
                FileUtils.copyInputStreamToFile(sourceFile.getInputStream(), f);
                CompareInfo compareInfo = compareRquest(f,head);
                String score = compareInfo.getScore();
                if(Double.parseDouble(score)>=Double.parseDouble(compareRate)){
                    Map<String, Object> paramsRel = new HashMap();
                    paramsRel.put("candidateId",candidate.getId());
                    paramsRel.put("isFinish",2);
                    CandidateRel candidateRel = candidateRelDao.getByParams(paramsRel);
                    candidateRel.setIsActive(1);
                    candidateRelDao.update(candidateRel);
                    CandidateCheck candidateCheck = new CandidateCheck();
                    candidateCheck.setIdCard(idCard);
                    candidateCheck.setCandidateRelId(candidateRel.getId());
                    candidateCheck.setCheckRate(score);
                    candidateCheck.setCreated(new Date());
                    candidateCheckService.add(candidateCheck);
                    return JsonResponse.success();
                }else {
                    return JsonResponse.fail("匹配相似度太低,相似度为:"+score);
                }
            }else {
                throw new Exception("该用户不存在或者该用户身份证头像不存在");
            }
        }
    
    private CompareInfo compareRquest(File file, File file2) throws Exception {
            OkHttpClient httpClient = new OkHttpClient();
            String sessionId = "";
            //先登录 获取sessionId ,post json方式
            Map<String,Object> loginParams = new HashMap<>();
            loginParams.put("msg_id","257");
            loginParams.put("user_name","admin");
            loginParams.put("user_pwd","admin");
    
            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(loginParams));
            String json = jsonObject.toJSONString();
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"),json);
            Request request = new Request.Builder()
                    .url(loginUrl)
                    .post(requestBody)
                    .build();
            Response response = httpClient.newCall(request).execute();
            String result = new String(response.body().bytes());
            JSONObject temp = (JSONObject) JSON.parse(result);
            if(Integer.parseInt(temp.get("code").toString())==0){
                sessionId = temp.get("data").toString();
            }else {
                throw new ConditionException(temp.toJSONString());
            }
    
            //调用接口  post form方式
            RequestBody fileBody = RequestBody.create(MediaType.parse("image/png"), file);//将file转换成RequestBody文件 这里以MP4视频为例
            RequestBody fileBody2 = RequestBody.create(MediaType.parse("image/png"), file2);//将file转换成RequestBody文件 这里以MP4视频为例
            RequestBody requestBody2 = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("msg_id", "771")
                    .addFormDataPart("img_1", "file1", fileBody)
                    .addFormDataPart("img_2", "file2", fileBody2)
                    .build();
    
            Request request2 = new Request.Builder()
                    .url(compareUrl)
                    .addHeader("sessionid",sessionId)
                    .post(requestBody2)
                    .build();
    
            Response response2 = httpClient.newCall(request2).execute();
            String result2 = new String(response2.body().bytes());
            JSONObject temp2 = (JSONObject) JSON.parse(result2);
            if(Integer.parseInt(temp2.get("code").toString())==0){
                JSONObject data = (JSONObject) JSON.parse(JSONObject.toJSONString(temp2.get("data")));
                CompareInfo compareInfo = new CompareInfo();
                compareInfo.setMsg(temp2.get("msg").toString());
                compareInfo.setScore(data.get("FaceImg1to1Rsp_Score").toString());
                return compareInfo;
            }else {
                throw new ConditionException(temp2.toJSONString());
            }
    
        }
    
    <dependency>
                <groupId>com.alibaba.csb.sdk</groupId>
                <artifactId>http-client</artifactId>
                <version>1.1.1</version>
            </dependency>
    
    展开全文
  • 1:创建一个OkHttpClient(发起请求的客户端) OkHttpClient.Builder builder = new OkHttpClient.Builder();//首先拿到创建者 builder.connectTimeout(30, TimeUnit.SECONDS); builder.readTimeout(30, TimeUni....

     1:创建一个OkHttpClient(发起请求的客户端)

            OkHttpClient.Builder builder = new OkHttpClient.Builder();//首先拿到创建者
            builder.connectTimeout(30, TimeUnit.SECONDS);
            builder.readTimeout(30, TimeUnit.SECONDS);
            OkHttpClient okHttpClient = builder.build();//由创建者创建OkHttpClient

    2:创建一个RequestBody(请求体:用于存放文件对象和别的参数)

           MultipartBody.Builder builder = new MultipartBody.Builder();//首先拿到创建者

           builder .setType(MediaType.parse("multipart/form-data"));//设置请求体类型
           File file = new File(文件路径);
           String fileType = getMimeType(file.getName());//根据文件的后缀名,获得文件类型
           builder.addFormDataPart("file",file.getName(),RequestBody.create(MediaType.parse(fileType), file));
           builder.addFormDataPart("description", 其他参数); 
           RequestBody requestBody = builder.build(); //由创建者创建RequestBody

    3:创建一个Request(请求对象:用于存放请求地址url和请求体RequestBody)

            Request.Builder builder = new Request.Builder();//首先拿到创建者
            builder.url(url)                                                       //设置请求地址
                    .method("POST", requestBody);               //设置requestBody

            //也可以这样写 :builder.url(url).post(requestBody)

          Request request = builder.build();//由创建者创建OkHttpClient

    4:创建Call(根据OkHttpClient和request创建call,call用于调用函数以发送请求)

         Call call = okHttpClient.newCall(request);

    5:用call调用函数以发送请求

    call.enqueue(失败的回调函数,成功的回调函数);

    注意:第5步是异步请求,关于同步请求和异步请求的区别请看下篇文章

    展开全文
  • java通过OkHttpClient发送https请求 之前使用过DefaHttpClient发送https一直没有成功,后面尝试OkHttpClient可以发送成功 pom文件配置 <dependency> <groupId>com.squareup.okhttp3</groupId> ...

    java通过OkHttpClient发送https请求

    之前使用过DefaHttpClient发送https一直没有成功,后面尝试OkHttpClient可以发送成功
    pom文件配置

    	<dependency>
    		  <groupId>com.squareup.okhttp3</groupId>
    		  <artifactId>okhttp</artifactId>
    		  <version>3.14.4</version>
    	  </dependency>
    

    java代码

    package com.msok.kettle.utils;
    
    import com.alibaba.fastjson.JSONArray;
    import com.alibaba.fastjson.JSONObject;
    import okhttp3.*;
    
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.SSLSocketFactory;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.X509TrustManager;
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.net.URLEncoder;
    import java.security.KeyManagementException;
    import java.security.NoSuchAlgorithmException;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.concurrent.TimeUnit;
    
    /**
     * @Author
     * @Description
     */
    public class OkHttpUtil {
        private final static int READ_TIMEOUT = 30;
    
        private final static int CONNECT_TIMEOUT = 20;
    
        private final static int WRITE_TIMEOUT = 20;
    
        public static OkHttpClient.Builder buildOKHttpClient() {
            try {
                TrustManager[] trustAllCerts = buildTrustManagers();
                final SSLContext sslContext = SSLContext.getInstance("SSL");
                sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
    
                final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
                OkHttpClient.Builder builder = new OkHttpClient.Builder();
                builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
                builder.hostnameVerifier((hostname, session) -> true);
                return builder;
            } catch (NoSuchAlgorithmException | KeyManagementException e) {
                e.printStackTrace();
                return new OkHttpClient.Builder();
            }
        }
    
        private static TrustManager[] buildTrustManagers() {
            return new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                        }
    
                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                        }
    
                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };
        }
    
        /**
         * @ Deprecated :map参数转为string
         * @param pmap
         * @return
         */
        public static String map2Url(Map<String, Object> pmap) {
            String postpar = "";
            // map格式的请求参数
            if(pmap!=null) {
                StringBuffer mstr = new StringBuffer();
                for (String str : pmap.keySet()) {
                    String val = (String) pmap.get(str);
                    try {
                        val = URLEncoder.encode(val, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    mstr.append(str + "=" + val + "&");
                }
                postpar = mstr.toString();
                int lasts=postpar.lastIndexOf("&");
                postpar=postpar.substring(0, lasts);
            }
            return postpar;
        }
        static Response response;
    
        /**
         * @ Deprecated :发送请求
         * @param json
         * @param url
         * @param pmap
         * @return
         */
        public static String sendByHttps(String json, String url,Map<String,Object> pmap) {
             String respContent = null;
            try{
                MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
                String pString = map2Url(pmap);
                if(pString!=null&pString.length()>0){
                    url+="?"+pString;
                }
                Request request = new Request.Builder()
                        .url(url)
                        .headers(Headers.of(new HashMap<>()))
                        .post(RequestBody.create(mediaType, json))
                        .build();
    
                OkHttpClient okHttpClient = buildOKHttpClient()
                        .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                        .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                        .writeTimeout(WRITE_TIMEOUT, TimeUnit.MILLISECONDS)
                        .build();
                 response = okHttpClient.newCall(request).execute();
    
                if(response.code()==200){
                    ResponseBody respBody = response.body();
                      respContent = respBody==null ? null:respBody.string();
                }
            }catch (IOException e){
                e.printStackTrace();
            }finally {
                if(response!=null){
                    response.close();
                }
            }
            return respContent;
        }
    
    
        public static void main(String[] args) {
        	//参数封装
            HashMap<String, Object> pmap = new HashMap<>();
            pmap.put("param","param");
            pmap.put("token","token");
            //url
            String url = "";
            //body
            String json = "";
            String s = sendByHttps(json, url, pmap);
            System.out.println(s);
    
        }
    }
    
    展开全文
  • // 加载客户端证书,即p12文件。 clientStore .load(new FileInputStream(CLIENT_CA_PATH), KEY_STORE_PWD.toCharArray()); // 创建密钥管理工厂实例 KeyManagerFactory kmf = KeyManagerFactory.getInstance...
  • RetrofitClient.getInstance(ElectricPayApplication.instance).getOkHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).build().newCall(request).enqueue(new Callback() { @Override public void ...
  • okhttp多文件上传

    2017-04-21 08:47:41
    使用okhttp进行多文件上传,包含服务器端代码
  • Okhttp3发送xml、json、文件的请求方法

    千次阅读 2019-05-28 08:22:57
      如果想了解xml与字符串之间的转换可以参考这个,...  以下仅仅包括post方式发送xml字符串、get请求获取json、post请求发送文件及参数这三种方法。 1、引入依赖 <dependency> <groupId>com.squa...
  • okHttpClient上传下载

    2018-11-13 20:00:24
    //创建上传文件对象 File file = new File(Environment.getExternalStorageDirectory() + "/Pictures/Screenshots", "meinv.png"); //创建RequestBody封装参数 RequestBody requestBody = RequestBody.create...
  • Java使用OKHttp携带参数上传文件 依赖:okhttp-3.9.0,okio-1.13.0 第一次发帖请见谅 时间:2020-8-5 14:51 前端: java 后端: php public static void uploadFile() throws IOException { OkHttpClient client =...
  • 下面对OkHttp做了一个简单的封装,可用于发送get、post请求(支持请求参数格式为键值对、json格式)、文件上传、文件下载。 package com.universe.thirdparty.okhttp; import java.io.IOException; import java....
  • 近日做了个接口需求,要求把json数据放入文件中,以文件的形式发送http报文请求,在网上找了好多种方式,都没能联调成功,最终用了OkHttpClient才实现了。 测试如下 util工具类 直接复制过去即可,什么都不用改。 ...
  • okhttp上传文件,包含Android客户端代码和Java Servlet服务端代码,本地测试通过。
  •  OkHttpClient okHttpClient = new OkHttpClient();  //2.创建一个请求的对象....默认就是get方式  Request request = new Request.Builder()  .url("https://www.zhaoapi.cn/ad/getAd")  .build...
  • OkHttpClient post的使用

    千次阅读 2017-11-29 14:30:39
    OkHttpClient okHttpClient=new OkHttpClient(); FormBody formboby=new FormBody.Builder() .add("mobile", "15715317583") .add("password", "123456") .build(); Request builder = new Request
  • 虽然在使用 OkHttp 发送 HTTP 请求时只需要提供 URL 即可,OkHttp 在实现中需要综合考虑 3 种不同的要素来确定与 HTTP 服务器之间实际建立的 HTTP 连接。这样做的目的是为了达到最佳的性能。 首先第一个考虑的要素是...
  • OkHttpClient

    2020-06-02 15:57:14
    OkHttpClient前期准备使用OkHttpClient创建对象getpost 前期准备 在日常开发中,使用http的请求已经是主流;在此过程中,如果我们要使用一些对接接口的时候,比如支付宝支付的接口,需要发起http的请求来获取结果,...
  • okhttp常规用法 try { OkHttpClient client=new OkHttpClient(); /** * 上传文件格式 */ /*RequestBody fileBody = RequestBody.create(MediaTy
  • OKHttp实现大文件的断点续传

    万次阅读 2017-02-25 00:02:23
    (1)网络请求用OKHttp进行下载大文件 (2)实现了大文件的断点续传 (3)取消下载时,删除已经下载的文件。 实现效果图:   直接给出工程: (1)定义一个接口:DownloadListener.java package ...
  • Android OkHttp Post上传文件并且携带参数 这里整理一下 OkHttp 的 post 在上传文件的同时,也要携带请求参数的方法。 ... OkHttpClient client = new OkHttpClient(); // form 表单形式上传 Mul
  • 最近工作中碰到一个生产问题,就是应用服务在使用 OkHttpClient 时,在创建大量对外连接时线程堆积导致内存溢出。 主要表现是在流量极低的情况下,即平均 qps 在 1~4 左右的情况下,各主要线程都很低,但是系统活跃...
  • OkHttp 获取文本、文件、Post请求

    千次阅读 2016-08-20 19:16:40
    OkHttp的简单使用,读取文本,下载文件,Post请求
  • OkHttpClient使用和封装

    千次阅读 2018-09-29 10:56:38
    引入库以后,需要在AndroidManifest文件中获取网络访问权限 < uses-permission android: name = " android.permission.INTERNET " /> 同步GET请求 //同步GET方法,execute()方法会抛出IOException异常...
  • SpringMvc接收file流为MultipartFile,需转为File ...1.先获取前台传的文件名称(获取文件名) String fileName = file.getOriginalFilename(); 2.获取文件后缀名称 String prefix=fileName.substring(fileNa...
  • 安卓使用OkHttpClient进行网络请求

    千次阅读 2016-05-13 00:02:40
    可以通过OkHttpClient减少代码量,源码为https://github.com/square/okhttpOkHttpClient的使用非常简单,也可以分为同步和异步两种。同步(Synchronous Get)首先引入Okhttpclient的依赖包compile '...
  • 客户端将文件转换为流发送: 依赖的包: <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.4</version>&...
  • okhttp post请求上传服务器File文件

    千次阅读 2017-09-29 11:22:13
    简单通俗易懂 public class HeadMobile { private HeadView headView; public void head(String mobile,File file){ OkHttpClient client=new OkHttpClient(); MultipartBody.Builder reque

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 3,842
精华内容 1,536
关键字:

okhttpclient发送文件