okhttp加头部信息请求范例

用header方法包含头部信息:header("cookie",s) .build(); 

public void sendSms(ConcurrentMap map) {
        String s=(String)SPUtil.get(mContext,Constants.COOKIE,"");
        Log.e("getSMSCode",s);
        RequestBody body=setRequestBody(map);
       // Log.e("发送短信","body="+body);
        Request.Builder requestBuilder = new Request.Builder();
        Request request = requestBuilder.post(body).url(NetWorkConfig.SEND_SMS_CODE).header("cookie",s) .build();
        OkHttpClient mOkHttpClient = new OkHttpClient.Builder().build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
               // mView.onError(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result=response.body().string();
//                SimpleInfo simpleInfo=new Gson().fromJson(result,SimpleInfo.class);
//                Log.e("发送短信","code="+simpleInfo.getCode());
                mView.setSmsReult(result);
            }
        });
    }
private RequestBody setRequestBody(ConcurrentMap BodyParams){
        RequestBody body=null;
        okhttp3.FormBody.Builder formEncodingBuilder=new okhttp3.FormBody.Builder();
        if(BodyParams != null){
            Iterator iterator = BodyParams.keySet().iterator();
            String key = "";
            while (iterator.hasNext()) {
                key = iterator.next().toString();
                formEncodingBuilder.add(key, BodyParams.get(key));
                Log.d("post http", "post_Params==="+key+"===="+BodyParams.get(key));
            }
        }
        body=formEncodingBuilder.build();
        return body;
    }


    public void getCheckCode(ConcurrentMap map) {
        String s=(String)SPUtil.get(mContext,Constants.COOKIE,"");
        RequestBody body=setRequestBody(map);
        // Log.e("发送短信","body="+body);
        Request.Builder requestBuilder = new Request.Builder();
        Request request = requestBuilder.post(body).url(NetWorkConfig.CHECK_CODE).header("cookie",s) .build();
        OkHttpClient mOkHttpClient = new OkHttpClient.Builder().build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // mView.onError(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result=response.body().string();
                mView.setCheckReult(result);
            }
        });
    }

 

 

你可能感兴趣的:(android)