Search in sources :

Example 36 with FormBody

use of okhttp3.FormBody in project Gradle-demo by Arisono.

the class LogInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    Map<String, Object> headers = new HashMap<>();
    Map<String, Object> params = new HashMap<>();
    Map<String, Object> postParm = new HashMap<>();
    //添加公共Header,公共参数
    if (builder != null) {
        headers = builder.getHeaders();
        params = builder.getParams();
        if (!headers.isEmpty()) {
            for (Map.Entry<String, Object> entry : headers.entrySet()) {
                request = request.newBuilder().addHeader(entry.getKey(), String.valueOf(entry.getValue())).build();
            }
        }
        if (!params.isEmpty()) {
            //get请求    添加公共参数
            if (request.method().equals("GET")) {
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    HttpUrl httpUrl = request.url().newBuilder().addQueryParameter(entry.getKey(), String.valueOf(entry.getValue())).build();
                    request = request.newBuilder().url(httpUrl).build();
                }
            }
            if (request.method().equals("POST")) {
                if (request.body() instanceof FormBody) {
                    FormBody.Builder bodyBuilder = new FormBody.Builder();
                    FormBody formBody = (FormBody) request.body();
                    for (int i = 0; i < formBody.size(); i++) {
                        postParm.put(formBody.encodedName(i), formBody.encodedValue(i));
                        bodyBuilder.addEncoded(formBody.encodedName(i), formBody.encodedValue(i));
                    }
                    for (Map.Entry<String, Object> entry : params.entrySet()) {
                        formBody = bodyBuilder.addEncoded(entry.getKey(), String.valueOf(entry.getValue())).build();
                    }
                    request = request.newBuilder().post(formBody).build();
                }
            }
        }
    }
    Response response = chain.proceed(request);
    okhttp3.MediaType mediaType = response.body().contentType();
    String content = response.body().string();
    if (true) {
        OkhttpUtils.println("|---------------日志打印  start---------------------------|");
        OkhttpUtils.println("请求头:" + JSON.toJSONString(response.request().headers().toMultimap()));
        OkhttpUtils.println("url:" + JSON.toJSONString(response.request().url().toString()));
        OkhttpUtils.println("参数:" + JSON.toJSONString(postParm));
        OkhttpUtils.println("结果:" + content);
        OkhttpUtils.println("|---------------日志打印   end---------------------------|");
    }
    return response.newBuilder().body(okhttp3.ResponseBody.create(mediaType, content)).build();
}
Also used : HashMap(java.util.HashMap) Request(okhttp3.Request) FormBody(okhttp3.FormBody) HttpUrl(okhttp3.HttpUrl) Response(okhttp3.Response) Map(java.util.Map) HashMap(java.util.HashMap)

Example 37 with FormBody

use of okhttp3.FormBody in project Gradle-demo by Arisono.

the class OkhttpUtils method sendPostHttp.

/** 
	 * post http
	 * @param url
	 * @param params
	 * @param tag
	 */
public static void sendPostHttp(String url, Map<String, Object> params, String cookies, String tag) {
    Builder paramBuilder = new FormBody.Builder();
    if (!params.isEmpty()) {
        Iterator<Map.Entry<String, Object>> entries = params.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String, Object> entry = entries.next();
            paramBuilder.add(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
        }
        OkhttpUtils.println(tag + ":" + url);
        RequestBody formBody = paramBuilder.build();
        Request request = new Request.Builder().url(url).addHeader("content-type", "text/html;charset:utf-8").addHeader("Cookie", cookies).post(formBody).build();
        OkhttpUtils.client.newCall(request).enqueue(new Callback() {

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String requestJson = OkhttpUtils.getResponseString(response);
                RxBus.getInstance().send(tag + ":" + requestJson);
            }

            @Override
            public void onFailure(Call call, IOException e) {
                OkhttpUtils.onFailurePrintln(call, e, this);
            }
        });
    }
}
Also used : Call(okhttp3.Call) Builder(okhttp3.FormBody.Builder) Request(okhttp3.Request) IOException(java.io.IOException) Response(okhttp3.Response) Callback(okhttp3.Callback) Map(java.util.Map) RequestBody(okhttp3.RequestBody)

Example 38 with FormBody

use of okhttp3.FormBody in project AndLang by wugemu.

the class HttpU method postArray.

/**
 * 网络请求方法
 *
 * @param context
 * @param url
 * @param params
 * @param tag
 * @param callback
 */
public void postArray(final Context context, final String url, Map<String, Object> params, Object tag, final HttpCallback callback) {
    if (context == null) {
        callback.onAfter();
        return;
    }
    String reqmsg = "";
    // token校验参数
    if (params == null) {
        params = new HashMap<String, Object>();
    }
    FormBody.Builder formBuilder = new FormBody.Builder();
    if (params != null && params.size() > 0) {
        Iterator iter = params.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            if (entry != null) {
                if (entry.getKey() != null && entry.getValue() != null) {
                    if (entry.getValue().toString().startsWith("[") && entry.getValue().toString().endsWith("]")) {
                        String value = entry.getValue().toString().substring(1, entry.getValue().toString().length() - 1);
                        String[] values = value.split(",");
                        for (int i = 0; i < values.length; i++) {
                            formBuilder.add(entry.getKey().toString(), values[i]);
                        }
                    } else {
                        formBuilder.add(entry.getKey().toString(), entry.getValue().toString());
                    }
                }
            }
        }
    }
    FormBody formBody = formBuilder.build();
    Request.Builder requestBuilder = new Request.Builder();
    final Request request = requestBuilder.url(url).post(formBody).tag(tag).build();
    Log.d(BaseLangPresenter.TAG, "请求报文Host:" + url);
    Log.d(BaseLangPresenter.TAG, "请求报文body:" + params);
    callback.onBefore(request);
    Call call = mOkHttpClient.newCall(request);
    call.enqueue(new Callback() {

        @Override
        public void onFailure(Call call, final IOException e) {
            handler.post(new Runnable() {

                @Override
                public void run() {
                    callback.onError(request, e, context);
                    Log.i("nyso_bbc", "onError" + e);
                    callback.onAfter();
                }
            });
        }

        @Override
        public void onResponse(Call call, final Response response) throws IOException {
            try {
                final String result = response.body().string();
                List<String> cookies = response.headers("Set-Cookie");
                String cookie = null;
                for (String str : cookies) {
                    Log.d(BaseLangPresenter.TAG, "返回报文cookie:" + str);
                }
                Log.d(BaseLangPresenter.TAG, "返回报文Host:" + url);
                Log.d(BaseLangPresenter.TAG, "返回报文body:" + result);
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        callback.onResponse(result);
                        callback.onAfter();
                    }
                });
            } catch (final Exception e) {
                e.printStackTrace();
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        callback.onError(request, e, context);
                        callback.onAfter();
                    }
                });
            }
        }
    });
}
Also used : Call(okhttp3.Call) FormBody(okhttp3.FormBody) Request(okhttp3.Request) IOException(java.io.IOException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) Response(okhttp3.Response) Callback(okhttp3.Callback) Iterator(java.util.Iterator) JSONObject(org.json.JSONObject) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map)

Example 39 with FormBody

use of okhttp3.FormBody in project Dxditor by kimi2009.

the class SpzModel method getWarningData.

@Override
public void getWarningData(final ValueCallBack<ArrayList<SpzWarning>> callBack) {
    if (Constants.testData) {
        ArrayList<SpzWarning> temp = new ArrayList<SpzWarning>();
        temp.add(new SpzWarning("", "京津线03号桥梁声屏障(2米处)声屏障位移", "120", "", "mm"));
        temp.add(new SpzWarning("", "丰沙线11号桥梁声屏障(0.9米处)声屏障位移", "80", "", "mm"));
        temp.add(new SpzWarning("", "京包线19号桥梁声屏障(2.4米处)声屏障位移", "74", "", "mm"));
        spzWarnings = temp;
        callBack.onSuccess(spzWarnings);
    } else {
        /*//Form表单格式的参数传递
        FormBody formBody = new FormBody
                .Builder()
                .add("bridgeCode", Constants.BRIDGECODE)//设置参数名称和参数值
                .build();*/
        Request request = new Request.Builder().url(Constants.getAppSoundBarrierNewOneAlarm).build();
        okHttpClient.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                System.out.println("getAppSoundBarrierNewOneAlarm:" + res);
                try {
                    JSONObject js = new JSONObject(res);
                    if (js.getBoolean("success")) {
                        spzWarnings = gson.fromJson(js.getString("data"), new TypeToken<ArrayList<SpzWarning>>() {
                        }.getType());
                        callBack.onSuccess(spzWarnings);
                    } else {
                        callBack.onFail("01");
                    }
                } catch (Exception e) {
                    callBack.onFail("01");
                    e.printStackTrace();
                }
            }
        });
    }
}
Also used : Call(okhttp3.Call) ArrayList(java.util.ArrayList) Request(okhttp3.Request) IOException(java.io.IOException) IOException(java.io.IOException) Response(okhttp3.Response) SpzWarning(itor.topnetwork.com.dxditor.bean.SpzWarning) Callback(okhttp3.Callback) JSONObject(org.json.JSONObject) TypeToken(com.google.gson.reflect.TypeToken)

Example 40 with FormBody

use of okhttp3.FormBody in project Dxditor by kimi2009.

the class BridgeModel method getWarningData.

@Override
public void getWarningData(final ValueCallBack<ArrayList<BridgeWarning>> callBack) {
    if (Constants.testData) {
        ArrayList<BridgeWarning> temp = new ArrayList<BridgeWarning>();
        temp.add(new BridgeWarning("京津线39号桥梁(中间)梁体应力", null, "3.5N", "2.3N", null, "1", null, null));
        temp.add(new BridgeWarning("京张铁路18号桥梁(中间)梁体裂缝宽度", null, "1.2cm", "1.1cm", null, "2", null, null));
        temp.add(new BridgeWarning("京沪线75号桥梁梁体横向位移", null, "0.6cm", "0.9cm", null, "3", null, null));
        bridgeWarnings = temp;
        callBack.onSuccess(bridgeWarnings);
    } else {
        FormBody formBody = new FormBody.Builder().add("bridgeCode", // 设置参数名称和参数值
        Constants.BRIDGECODE).build();
        Request request = new Request.Builder().post(formBody).url(Constants.getAppBridgeNewOneAlarm).build();
        okHttpClient.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                try {
                    JSONObject js = new JSONObject(res);
                    if (js.getBoolean("success")) {
                        bridgeWarnings = gson.fromJson(js.getString("data"), new TypeToken<ArrayList<BridgeWarning>>() {
                        }.getType());
                        callBack.onSuccess(bridgeWarnings);
                    } else {
                        callBack.onFail("01");
                    }
                } catch (Exception e) {
                    callBack.onFail("01");
                    e.printStackTrace();
                }
            }
        });
    }
}
Also used : Call(okhttp3.Call) ArrayList(java.util.ArrayList) FormBody(okhttp3.FormBody) Request(okhttp3.Request) IOException(java.io.IOException) BridgeWarning(itor.topnetwork.com.dxditor.bean.BridgeWarning) IOException(java.io.IOException) Response(okhttp3.Response) Callback(okhttp3.Callback) JSONObject(org.json.JSONObject) TypeToken(com.google.gson.reflect.TypeToken)

Aggregations

Request (okhttp3.Request)61 Response (okhttp3.Response)58 FormBody (okhttp3.FormBody)53 RequestBody (okhttp3.RequestBody)43 IOException (java.io.IOException)39 Call (okhttp3.Call)32 Callback (okhttp3.Callback)29 JSONObject (org.json.JSONObject)20 Map (java.util.Map)15 HttpUrl (okhttp3.HttpUrl)10 OkHttpClient (okhttp3.OkHttpClient)10 MultipartBody (okhttp3.MultipartBody)9 HashMap (java.util.HashMap)8 ArrayList (java.util.ArrayList)6 MediaType (okhttp3.MediaType)6 TypeToken (com.google.gson.reflect.TypeToken)4 File (java.io.File)3 DataInputStream (java.io.DataInputStream)2 List (java.util.List)2 ProgressRequestBody (me.ccrama.redditslide.util.ProgressRequestBody)2