How to fix the code to correctly send form-data:

private static Request request = null; private static OkHttpClient client= new OkHttpClient.Builder() .cookieJar(new CookieJar() { private final HashMap<HttpUrl, List<Cookie>> cookieStore = new HashMap<>(); @Override public void saveFromResponse(HttpUrl url, List<Cookie> cookies) { cookieStore.put(url, cookies); } @Override public List<Cookie> loadForRequest(HttpUrl url) { List<Cookie> cookies = cookieStore.get(url); return cookies != null ? cookies : new ArrayList<Cookie>(); } }).build(); RequestBody formBody = new FormBody.Builder() .add("user_name", "значение-1") .add("user_pass", "значение-2") .build(); request = new Request.Builder() .url("https://сайт.ru/") .post(formBody) .build(); System.out.println(client .newCall(request) .execute().body().string()); 

I make the exact same request through postman, but the site's responses differ. Maybe I do not write correctly in androyd or something missing ?? postman: enter image description here

And the request in the postmana code in java looks like this:

 OkHttpClient client = new OkHttpClient(); MediaType mediaType = MediaType.parse("multipart/form-data; boundary=---- WebKitFormBoundary7MA4YWxkTrZu0gW"); RequestBody body = RequestBody.create(mediaType, "------ WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"user_name\"\r\n\r\nЗначение-1\r\n------ WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"user_pass\"\r\n\r\nЗначение2\r\n------ WebKitFormBoundary7MA4YWxkTrZu0gW--"); Request request = new Request.Builder().url("https://сайт.ru/").post(body).addHeader("content-type", "multipart/form-data; boundary=---- WebKitFormBoundary7MA4YWxkTrZu0gW").addHeader("Content-Type", "application/x-www-form-urlencoded").addHeader("Cache-Control", "no-cache").addHeader("Postman-Token", "2c124ba6-7bef-772d-404d-8136f5166b45").build(); Response response = client.newCall(request).execute(); 

    1 answer 1

    When sending from postman MediaType = multipart/form-data , to create a similar request manually, use MultipartBody.Builder :

     RequestBody partFormBody = new FormBody.Builder() .add("user_name", "значение-1") .add("user_pass", "значение-2") .build(); RequestBody formBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addPart(partFormBody) .build(); 
    • request = new Request.Builder () .url (" site.ru /" ) .post (formBody) .build (); Here is the code, but it still does not work. - chilo5432
    • @ Artem Shelomentsov, updated the answer - try this - Nikolay
    • It doesn't work, you can see somewhere what exactly postman sends and what android sends - chilo5432