Search in sources :

Example 6 with FormBody

use of okhttp3.FormBody in project ignite by apache.

the class RestExecutor method sendRequest0.

/**
 */
private RestResult sendRequest0(String nodeUrl, boolean demo, String path, Map<String, Object> params, Map<String, Object> headers, String body) throws IOException {
    if (demo && AgentClusterDemo.getDemoUrl() == null) {
        try {
            AgentClusterDemo.tryStart().await();
        } catch (InterruptedException ignore) {
            throw new IllegalStateException("Failed to send request because of embedded node for demo mode is not started yet.");
        }
    }
    String url = demo ? AgentClusterDemo.getDemoUrl() : nodeUrl;
    HttpUrl httpUrl = HttpUrl.parse(url);
    if (httpUrl == null)
        throw new IllegalStateException("Failed to send request because of node URL is invalid: " + url);
    HttpUrl.Builder urlBuilder = httpUrl.newBuilder();
    if (path != null)
        urlBuilder.addPathSegment(path);
    final Request.Builder reqBuilder = new Request.Builder();
    if (headers != null) {
        for (Map.Entry<String, Object> entry : headers.entrySet()) if (entry.getValue() != null)
            reqBuilder.addHeader(entry.getKey(), entry.getValue().toString());
    }
    if (body != null) {
        MediaType contentType = MediaType.parse("text/plain");
        reqBuilder.post(RequestBody.create(contentType, body));
    } else {
        FormBody.Builder formBody = new FormBody.Builder();
        if (params != null) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                if (entry.getValue() != null)
                    formBody.add(entry.getKey(), entry.getValue().toString());
            }
        }
        reqBuilder.post(formBody.build());
    }
    reqBuilder.url(urlBuilder.build());
    try (Response resp = httpClient.newCall(reqBuilder.build()).execute()) {
        if (resp.isSuccessful()) {
            RestResponseHolder res = MAPPER.readValue(resp.body().byteStream(), RestResponseHolder.class);
            int status = res.getSuccessStatus();
            switch(status) {
                case STATUS_SUCCESS:
                    return RestResult.success(res.getResponse());
                default:
                    return RestResult.fail(status, res.getError());
            }
        }
        if (resp.code() == 401)
            return RestResult.fail(STATUS_AUTH_FAILED, "Failed to authenticate in cluster. " + "Please check agent\'s login and password or node port.");
        if (resp.code() == 404)
            return RestResult.fail(STATUS_FAILED, "Failed connect to cluster.");
        return RestResult.fail(STATUS_FAILED, "Failed to execute REST command: " + resp.message());
    }
}
Also used : Request(okhttp3.Request) FormBody(okhttp3.FormBody) HttpUrl(okhttp3.HttpUrl) Response(okhttp3.Response) MediaType(okhttp3.MediaType) HashMap(java.util.HashMap) Map(java.util.Map)

Example 7 with FormBody

use of okhttp3.FormBody in project protools by SeanDragon.

the class ToolSendHttp method convertRequest.

private static Request convertRequest(HttpSend httpSend) {
    final Request.Builder requestBuilder = new Request.Builder();
    final FormBody.Builder formBodyBuilder = new FormBody.Builder();
    final Map<String, Object> params = httpSend.getParams();
    final String url = httpSend.getUrl();
    final Map<String, Object> headers = httpSend.getHeaders();
    if (params != null) {
        params.forEach((key, value) -> {
            String v;
            if (value instanceof AbstractCollection || value instanceof Map || value instanceof Number || value instanceof String) {
                v = value.toString();
            } else {
                v = ToolJson.anyToJson(value);
            }
            formBodyBuilder.add(key, v);
        });
    }
    if (headers != null) {
        headers.forEach((key, value) -> {
            if (value instanceof AbstractCollection || value instanceof Map || value instanceof Number || value instanceof String) {
                requestBuilder.addHeader(key, value.toString());
            } else {
                requestBuilder.addHeader(key, ToolJson.anyToJson(value));
            }
        });
    }
    final FormBody requestBody = formBodyBuilder.build();
    if (httpSend.getMethod() == HttpMethod.GET) {
        return requestBuilder.url(url).build();
    } else {
        return requestBuilder.url(url).method(httpSend.getMethod().name(), requestBody).build();
    }
}
Also used : Request(okhttp3.Request) FormBody(okhttp3.FormBody) AbstractCollection(java.util.AbstractCollection) Map(java.util.Map)

Example 8 with FormBody

use of okhttp3.FormBody in project Dxditor by kimi2009.

the class SpzModel method getTrendData.

@Override
public void getTrendData(final ValueCallBack<String> callBack, int position) {
    spzTrends = new ArrayList<SpzTrend>();
    if (Constants.testData) {
        SpzEchartsBean spzBean = new SpzEchartsBean();
        if (position == 0) {
            for (int i = 0; i < 9; i++) {
                spzTrends.add(new SpzTrend(Float.parseFloat("10" + i), "03-2" + i + " 08:00"));
            }
        } else if (position == 1) {
            for (int i = 0; i < 9; i++) {
                spzTrends.add(new SpzTrend(Float.parseFloat("8" + i), "03-2" + i + " 08:00"));
            }
        } else if (position == 2) {
            for (int i = 0; i < 9; i++) {
                spzTrends.add(new SpzTrend(Float.parseFloat("7" + i), "03-2" + i + " 08:00"));
            }
        }
        List<String> time = new ArrayList<>();
        for (int i = 0; i < spzTrends.size(); i++) {
            time.add(spzTrends.get(i).getStorageTime());
        }
        spzBean.xData = time;
        List<Float> lineDatas = new ArrayList<>();
        for (int i = 0; i < spzTrends.size(); i++) {
            lineDatas.add(spzTrends.get(i).getTypeData());
        }
        spzBean.seriesData = lineDatas;
        callBack.onSuccess(gson.toJson(spzBean));
    } else {
        // Form表单格式的参数传递
        FormBody formBody = new FormBody.Builder().add("bridgeCode", spzWarnings.get(position).getBridgeCode()).add("type", spzWarnings.get(position).getType()).add("storageTime", Constants.MONTH).build();
        Request request = new Request.Builder().post(formBody).url(Constants.getAppSoundBarrierInfo).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("getAppSoundBarrierInfo:" + res);
                try {
                    JSONObject js = new JSONObject(res);
                    if (js.getBoolean("success")) {
                        spzTrends = gson.fromJson(js.getString("data"), new TypeToken<ArrayList<SpzTrend>>() {
                        }.getType());
                        SpzEchartsBean spzBean = new SpzEchartsBean();
                        // bridgeBean.initValue =;
                        List<String> time = new ArrayList<>();
                        for (int i = 0; i < spzTrends.size(); i++) {
                            time.add(spzTrends.get(i).getStorageTime());
                        }
                        spzBean.xData = time;
                        List<Float> lineDatas = new ArrayList<>();
                        for (int i = 0; i < spzTrends.size(); i++) {
                            lineDatas.add(spzTrends.get(i).getTypeData());
                        }
                        spzBean.seriesData = lineDatas;
                        callBack.onSuccess(gson.toJson(spzBean));
                    } 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) IOException(java.io.IOException) Response(okhttp3.Response) Callback(okhttp3.Callback) JSONObject(org.json.JSONObject) TypeToken(com.google.gson.reflect.TypeToken) SpzEchartsBean(itor.topnetwork.com.dxditor.hybrid.bean.spz.SpzEchartsBean) ArrayList(java.util.ArrayList) List(java.util.List) SpzTrend(itor.topnetwork.com.dxditor.bean.SpzTrend)

Example 9 with FormBody

use of okhttp3.FormBody in project Dxditor by kimi2009.

the class EchartsDataBean method ztLiveEcharts.

public void ztLiveEcharts(String code) {
    FormBody formBody = new FormBody.Builder().add("weightsCode", // 设置参数名称和参数值
    code).build();
    Request request = new Request.Builder().post(formBody).url(Constants.getAppWeightsTrendInfo).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("res:"+res);
            try {
                JSONObject js = new JSONObject(res);
                if (js.getBoolean("success")) {
                    ArrayList<ZtLiveBean> ZtLiveBeans = gson.fromJson(js.getString("data"), new TypeToken<ArrayList<ZtLiveBean>>() {
                    }.getType());
                    System.out.println("ZtLiveBeans.size():" + ZtLiveBeans.size());
                    ArrayList<String> xdata = new ArrayList<String>();
                    for (int i = 0; i < ZtLiveBeans.size(); i++) {
                        String time = ZtLiveBeans.get(i).getTimeStamp().replace("T", " ");
                        xdata.add(time);
                    }
                    ztLiveEchartsBean.xData = xdata;
                    /*ArrayList<Float> seriesdata = new ArrayList<Float>();
                        for (int i = 0; i < ZtLiveBeans.size(); i++) {
                            Float h = ZtLiveBeans.get(i).getbValue() + ZtLiveBeans.get(i).getWeightsHeight();
                            seriesdata.add(h);
                        }
                        ztLiveEchartsBean.seriesData = seriesdata;*/
                    ArrayList<Float> aValues = new ArrayList<Float>();
                    for (int i = 0; i < ZtLiveBeans.size(); i++) {
                        aValues.add(ZtLiveBeans.get(i).getaValue());
                    }
                    ztLiveEchartsBean.aValues = aValues;
                    ArrayList<Float> bValues = new ArrayList<Float>();
                    for (int i = 0; i < ZtLiveBeans.size(); i++) {
                        bValues.add(ZtLiveBeans.get(i).getbValue());
                    }
                    ztLiveEchartsBean.bValues = bValues;
                    ArrayList<Integer> temps = new ArrayList<Integer>();
                    for (int i = 0; i < ZtLiveBeans.size(); i++) {
                        temps.add(ZtLiveBeans.get(i).getTemperature());
                    }
                    ztLiveEchartsBean.temps = temps;
                    ztLiveEchartsBean.startValue = ZtLiveBeans.size() - 50;
                    ztLiveEchartsBean.endValue = ZtLiveBeans.size();
                } else {
                }
                ei.refresh(gson.toJson(ztLiveEchartsBean));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}
Also used : Call(okhttp3.Call) FormBody(okhttp3.FormBody) Request(okhttp3.Request) ArrayList(java.util.ArrayList) IOException(java.io.IOException) IOException(java.io.IOException) Response(okhttp3.Response) Callback(okhttp3.Callback) JSONObject(org.json.JSONObject)

Example 10 with FormBody

use of okhttp3.FormBody in project tutorials by eugenp.

the class OkHttpPostingLiveTest method whenSendPostRequest_thenCorrect.

@Test
public void whenSendPostRequest_thenCorrect() throws IOException {
    final RequestBody formBody = new FormBody.Builder().add("username", "test").add("password", "test").build();
    final Request request = new Request.Builder().url(BASE_URL + "/users").post(formBody).build();
    final Call call = client.newCall(request);
    final Response response = call.execute();
    assertThat(response.code(), equalTo(200));
}
Also used : Response(okhttp3.Response) Call(okhttp3.Call) FormBody(okhttp3.FormBody) Request(okhttp3.Request) RequestBody(okhttp3.RequestBody) Test(org.junit.Test)

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