Search in sources :

Example 26 with FormBody

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

the class testUASApi method saveFormData.

/**
 * 动态表单保存 接口
 */
public static void saveFormData() {
    String url = baseurl + "/mobile/oa/commonSaveAndSubmit.action";
    OkhttpUtils.println(url);
    RequestBody formBody = new FormBody.Builder().add("master", master).add("gridStore", "null").add("formStore", "{\"va_holidaytype\":\"按小时\",\"va_vacationtype\":\"事假\",\"va_status\":\"在录入\",\"va_emcode\":\"sunquan\",\"va_emname\":\"龚鹏明\",\"va_department\":\"测试\",\"va_position\":\"测试\",\"va_mankind\":\"副总及以上\",\"va_alldays\":\"12\",\"va_alltimes\":\"25\",\"va_startime\":\"2016-11-28 13:39:00\",\"va_remark\":\"测试\",\"va_recordor\":\"刘佳\",\"va_date\":\"2016-11-28 13:39:00\",\"va_endtime\":\"2016-12-28 13:39:00\"}").add("caller", "Ask4Leave").add("sessionId", sessionId).build();
    Request request = new Request.Builder().url(url).header("cookie", "JSESSIONID=" + sessionId).addHeader("sessionUser", emcode).addHeader("content-type", "text/html;charset:utf-8").post(formBody).build();
    OkhttpUtils.client.newCall(request).enqueue(new Callback() {

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            OkhttpUtils.println(OkhttpUtils.getResponseString(response));
        }

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

Example 27 with FormBody

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

the class OkhttpUtilsMain method sendFormParams.

/**
 * 表单提交
 */
public static void sendFormParams() {
    Map<String, Object> publicMap = RSAEncodeToken();
    String miwen = (String) publicMap.get("miwen");
    String public_key = (String) publicMap.get("public_key");
    RequestBody formBody = new FormBody.Builder().add("username", "123").add("password", "df13edafsdddsads").add("publicKey", public_key).add("miwen", miwen).build();
    // postBody 接收
    String json_1 = "{}";
    @SuppressWarnings("unused") String bytes = "username=123&password=df13edafsdddsads";
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url("http://localhost:8080/spring-mvc-showcase/http/getHeaders").header("cookie", "JSESSIONID=EB36DE5E50E342D86C55DAE0CDDD4F6D").addHeader("content-type", "text/html;charset:utf-8").post(RequestBody.create(JSONTYPE, json_1)).post(formBody).build();
    try {
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            String json = response.body().string();
            System.out.println(json);
        } else {
            System.out.println(JSON.toJSONString(response.code()));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("******************************************************");
}
Also used : Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) FormBody(okhttp3.FormBody) Request(okhttp3.Request) IOException(java.io.IOException) RequestBody(okhttp3.RequestBody)

Example 28 with FormBody

use of okhttp3.FormBody in project PokeGOAPI-Java by Grover-c13.

the class PtcCredentialProvider method login.

/**
 * Starts a login flow for pokemon.com (PTC) using a username and password,
 * this uses pokemon.com's oauth endpoint and returns a usable AuthInfo without user interaction
 *
 * @param username PTC username
 * @param password PTC password
 * @param attempt the current attempt index
 * @throws LoginFailedException if an exception occurs while attempting to log in
 * @throws InvalidCredentialsException if invalid credentials are used
 */
private void login(String username, String password, int attempt) throws LoginFailedException, InvalidCredentialsException {
    try {
        // TODO: stop creating an okhttp client per request
        Response getResponse;
        try {
            getResponse = client.newCall(new Request.Builder().url(HttpUrl.parse("https://sso.pokemon.com/sso/oauth2.0/authorize").newBuilder().addQueryParameter("client_id", CLIENT_ID).addQueryParameter("redirect_uri", REDIRECT_URI).addQueryParameter("locale", "en").build()).get().build()).execute();
        } catch (IOException e) {
            throw new LoginFailedException("Failed to receive contents from server", e);
        }
        Moshi moshi = new Moshi.Builder().build();
        PtcAuthJson ptcAuth;
        try {
            ptcAuth = moshi.adapter(PtcAuthJson.class).fromJson(getResponse.body().string());
        } catch (IOException e) {
            throw new LoginFailedException("Looks like the servers are down", e);
        }
        Response postResponse;
        try {
            FormBody postForm = new Builder().add("lt", ptcAuth.lt).add("execution", ptcAuth.execution).add("_eventId", "submit").add("username", username).add("password", password).add("locale", "en_US").build();
            HttpUrl loginPostUrl = HttpUrl.parse(LOGIN_URL).newBuilder().addQueryParameter("service", SERVICE_URL).build();
            Request postRequest = new Request.Builder().url(loginPostUrl).post(postForm).build();
            // Need a new client for this to not follow redirects
            postResponse = client.newBuilder().followRedirects(false).followSslRedirects(false).build().newCall(postRequest).execute();
        } catch (IOException e) {
            throw new LoginFailedException("Network failure", e);
        }
        String postBody;
        try {
            postBody = postResponse.body().string();
        } catch (IOException e) {
            throw new LoginFailedException("Response body fetching failed", e);
        }
        List<Cookie> cookies = client.cookieJar().loadForRequest(HttpUrl.parse(LOGIN_URL));
        for (Cookie cookie : cookies) {
            if (cookie.name().startsWith("CASTGC")) {
                this.tokenId = cookie.value();
                expiresTimestamp = time.currentTimeMillis() + 7140000L;
                return;
            }
        }
        if (postBody.length() > 0) {
            try {
                String[] errors = moshi.adapter(PtcAuthError.class).fromJson(postBody).errors;
                if (errors != null && errors.length > 0) {
                    throw new InvalidCredentialsException(errors[0]);
                }
            } catch (IOException e) {
                throw new LoginFailedException("Failed to parse ptc error json");
            }
        }
    } catch (LoginFailedException e) {
        if (shouldRetry && attempt < MAXIMUM_RETRIES) {
            login(username, password, ++attempt);
        } else {
            throw new LoginFailedException("Exceeded maximum login retries", e);
        }
    }
}
Also used : Cookie(okhttp3.Cookie) Moshi(com.squareup.moshi.Moshi) Builder(okhttp3.FormBody.Builder) FormBody(okhttp3.FormBody) Request(okhttp3.Request) IOException(java.io.IOException) HttpUrl(okhttp3.HttpUrl) Response(okhttp3.Response) LoginFailedException(com.pokegoapi.exceptions.request.LoginFailedException) InvalidCredentialsException(com.pokegoapi.exceptions.request.InvalidCredentialsException)

Example 29 with FormBody

use of okhttp3.FormBody in project AndLang by wugemu.

the class HttpU method post.

/**
 * 网络请求方法
 *
 * @param context
 * @param url
 * @param params
 * @param tag
 * @param callback
 */
public void post(final Context context, final String url, Map<String, Object> params, Object tag, final HttpCallback callback) {
    if (context == null) {
        callback.onAfter();
        return;
    }
    // token校验参数
    if (params == null) {
        params = new HashMap<String, Object>();
    }
    FormBody.Builder formBuilder = new FormBody.Builder();
    if (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) {
                    formBuilder.add(entry.getKey().toString(), entry.getValue().toString());
                }
            }
        }
    }
    FormBody formBody = formBuilder.build();
    String cookie = BaseLangApplication.getInstance().getSpUtil().getString(context, COOKIE);
    if (cookie != null && !"".equals(cookie)) {
        try {
            cookie = Des3.decode(cookie);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    Request.Builder requestBuilder = new Request.Builder();
    if (cookie != null) {
        requestBuilder.header(COOKIE, cookie);
    }
    final Request request = requestBuilder.url(url).post(formBody).tag(url).build();
    if (BaseLangUtil.isApkInDebug()) {
        AppCrashHandler crashHandler = AppCrashHandler.getInstance();
        if (crashHandler != null) {
            crashHandler.saveLogInfo2File("post请求报文Host:" + url);
            crashHandler.saveLogInfo2File("post请求报文cookie:" + cookie);
            crashHandler.saveLogInfo2File("post请求报文body:" + params);
        }
    }
    callback.onBefore(request);
    Call call = mOkHttpClient.newCall(request);
    call.enqueue(new Callback() {

        @Override
        public void onFailure(Call call, final IOException e) {
            onMyFailure(callback, request, e);
        }

        @Override
        public void onResponse(Call call, final Response response) throws IOException {
            onMyResponse(response, context, url, callback, request);
        }
    });
}
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) AppCrashHandler(com.example.test.andlang.log.AppCrashHandler) Callback(okhttp3.Callback) Iterator(java.util.Iterator) JSONObject(org.json.JSONObject) Map(java.util.Map) HashMap(java.util.HashMap) MimeTypeMap(android.webkit.MimeTypeMap)

Example 30 with FormBody

use of okhttp3.FormBody in project instagram-java-scraper by postaddictme.

the class Instagram method login.

public void login(String username, String password) throws IOException {
    if (username == null || password == null) {
        throw new InstagramAuthException("Specify username and password");
    } else if (this.csrf_token.isEmpty()) {
        throw new NullPointerException("Please run before base()");
    }
    RequestBody formBody = new FormBody.Builder().add("username", username).add("password", password).add("queryParams", "{}").add("optIntoOneTap", "true").build();
    Request request = new Request.Builder().url(Endpoint.LOGIN_URL).header(Endpoint.REFERER, Endpoint.BASE_URL + "/accounts/login/").post(formBody).build();
    Response response = executeHttpRequest(withCsrfToken(request));
    try (InputStream jsonStream = response.body().byteStream()) {
        if (!mapper.isAuthenticated(jsonStream)) {
            throw new InstagramAuthException("Credentials rejected by instagram", ErrorType.UNAUTHORIZED);
        }
    }
}
Also used : Response(okhttp3.Response) ActionResponse(me.postaddict.instagram.scraper.model.ActionResponse) InstagramAuthException(me.postaddict.instagram.scraper.exception.InstagramAuthException) DataInputStream(java.io.DataInputStream) InputStream(java.io.InputStream) FormBody(okhttp3.FormBody) GetMediaByTagRequest(me.postaddict.instagram.scraper.request.GetMediaByTagRequest) GetLocationRequest(me.postaddict.instagram.scraper.request.GetLocationRequest) GetMediasRequest(me.postaddict.instagram.scraper.request.GetMediasRequest) GetMediaLikesRequest(me.postaddict.instagram.scraper.request.GetMediaLikesRequest) Request(okhttp3.Request) GetFollowsRequest(me.postaddict.instagram.scraper.request.GetFollowsRequest) GetFollowersRequest(me.postaddict.instagram.scraper.request.GetFollowersRequest) RequestBody(okhttp3.RequestBody)

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