Skip to content

Explicitly set MediaType for different body types#164

Open
ddzobov wants to merge 3 commits intomattermost:masterfrom
ddzobov:patch-1
Open

Explicitly set MediaType for different body types#164
ddzobov wants to merge 3 commits intomattermost:masterfrom
ddzobov:patch-1

Conversation

@ddzobov
Copy link
Copy Markdown

@ddzobov ddzobov commented Apr 14, 2026

Summary

If Mattermost server published behind WAF, then WAF may block requests from Android clients, because by default it not sending any Content-Type headers in POST requests.

okhttp3 not sets Content-Type headers by default, so we need to do this explicitly.

mattermost/mattermost-mobile#9689

Implicit set MediaType for different body types
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 14, 2026

Warning

Rate limit exceeded

@ddzobov has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 47 minutes and 27 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 47 minutes and 27 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 6bc3c161-844e-4160-a39e-42be9d998244

📥 Commits

Reviewing files that changed from the base of the PR and between cfc500b and d79b41d.

📒 Files selected for processing (1)
  • android/src/main/java/com/mattermost/networkclient/NetworkClient.kt
📝 Walkthrough

Walkthrough

Modified the prepareRequestBody method in NetworkClient to explicitly specify MediaType when creating OkHttp RequestBody objects. JSON types now use application/json; charset=utf-8 while primitive types use text/plain; charset=utf-8, replacing previous implicit media type defaults.

Changes

Cohort / File(s) Summary
Request Body MediaType Specification
android/src/main/java/com/mattermost/networkclient/NetworkClient.kt
Added explicit MediaType parameters to toRequestBody() calls: JSON types (JSONArray, JSONObject) now use application/json; charset=utf-8, primitive types (String, Boolean, Number) use text/plain; charset=utf-8. Null handling unchanged.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: explicitly setting MediaType for different body types in the NetworkClient request body creation logic.
Description check ✅ Passed The PR description clearly explains the issue (WAF blocking requests without Content-Type headers) and links it to the changeset (explicitly setting MediaType for request bodies in NetworkClient).

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
android/src/main/java/com/mattermost/networkclient/NetworkClient.kt (1)

424-436: ⚠️ Potential issue | 🟠 Major

POST requests with null/missing body lack explicit Content-Type header.

Lines 425 and 435 use EMPTY_REQUEST without setting a media type, while all other body types (Array, Map, String, Boolean, Number) explicitly set media types via MediaType.parse(). This inconsistency can cause WAF or server-side validation to reject empty-body POST requests that lack a Content-Type header. Align these cases with the existing pattern.

Suggested fix
                    ReadableType.Null -> {
-                        requestBody = EMPTY_REQUEST
+                        requestBody = "".toRequestBody(MediaType.parse("text/plain; charset=utf-8"))
                    }
             } else if (method.uppercase(Locale.ENGLISH) == "POST") {
-                requestBody = EMPTY_REQUEST
+                requestBody = "".toRequestBody(MediaType.parse("text/plain; charset=utf-8"))
             }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@android/src/main/java/com/mattermost/networkclient/NetworkClient.kt` around
lines 424 - 436, When the request body is null or omitted the code currently
assigns EMPTY_REQUEST (in NetworkClient.kt) which provides no Content-Type;
update the null-body branch and the POST-without-body branch to create an empty
RequestBody with an explicit media type (match the other branches'
MediaType.parse("text/plain; charset=utf-8") usage) instead of raw EMPTY_REQUEST
so the resulting request always has a Content-Type header; adjust any use of
EMPTY_REQUEST in the branches handling ReadableType.Null and the
method.uppercase(...) == "POST" check (and factor into a named
EMPTY_REQUEST_WITH_MEDIA constant if helpful) so behavior is consistent with
String/Boolean/Number branches.
🧹 Nitpick comments (1)
android/src/main/java/com/mattermost/networkclient/NetworkClient.kt (1)

411-431: Replace repeated MediaType.parse() calls with class-level constants using toMediaType().

The code parses the same two media type strings five times. Add class-level constants and import toMediaType() to eliminate redundant parsing and improve performance.

Suggested refactor
@@
 import okhttp3.*
 import okhttp3.RequestBody.Companion.toRequestBody
+import okhttp3.MediaType.Companion.toMediaType
@@
 internal class NetworkClient(private val context: Context, private val baseUrl: HttpUrl? = null, options: ReadableMap? = null, cookieJar: CookieJar? = null) {
     private var okHttpClient: OkHttpClient
+    private val jsonUtf8MediaType = "application/json; charset=utf-8".toMediaType()
+    private val textUtf8MediaType = "text/plain; charset=utf-8".toMediaType()
@@
 requestBody = jsonBody.toString().toRequestBody(MediaType.parse("application/json; charset=utf-8"))
-                        requestBody = jsonBody.toString().toRequestBody(jsonUtf8MediaType)
+                        requestBody = jsonBody.toString().toRequestBody(jsonUtf8MediaType)
@@
 requestBody = jsonBody?.toString()?.toRequestBody(MediaType.parse("application/json; charset=utf-8"))
-                        requestBody = jsonBody?.toString()?.toRequestBody(jsonUtf8MediaType)
+                        requestBody = jsonBody?.toString()?.toRequestBody(jsonUtf8MediaType)
@@
 requestBody = options.getString("body")!!.toRequestBody(MediaType.parse("text/plain; charset=utf-8"))
-                        requestBody = options.getString("body")!!.toRequestBody(textUtf8MediaType)
+                        requestBody = options.getString("body")!!.toRequestBody(textUtf8MediaType)
@@
 requestBody = options.getBoolean("body").toString().toRequestBody(MediaType.parse("text/plain; charset=utf-8"))
-                        requestBody = options.getBoolean("body").toString().toRequestBody(textUtf8MediaType)
+                        requestBody = options.getBoolean("body").toString().toRequestBody(textUtf8MediaType)
@@
 requestBody = options.getDouble("body").toString().toRequestBody(MediaType.parse("text/plain; charset=utf-8"))
-                        requestBody = options.getDouble("body").toString().toRequestBody(textUtf8MediaType)
+                        requestBody = options.getDouble("body").toString().toRequestBody(textUtf8MediaType)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@android/src/main/java/com/mattermost/networkclient/NetworkClient.kt` around
lines 411 - 431, Replace repeated MediaType.parse() calls by declaring
class-level constants (e.g., MEDIA_TYPE_JSON and MEDIA_TYPE_TEXT) using the
okhttp3 extension toMediaType() and reuse them when creating requestBody in
NetworkClient.kt; add the import okhttp3.MediaType.Companion.toMediaType, define
something like private val MEDIA_TYPE_JSON = "application/json;
charset=utf-8".toMediaType() and private val MEDIA_TYPE_TEXT = "text/plain;
charset=utf-8".toMediaType(), then update the requestBody assignments in the
body-handling switch (the ReadableType.Map/String/Boolean/Number branches) to
pass MEDIA_TYPE_JSON or MEDIA_TYPE_TEXT instead of calling MediaType.parse()
repeatedly.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@android/src/main/java/com/mattermost/networkclient/NetworkClient.kt`:
- Around line 424-436: When the request body is null or omitted the code
currently assigns EMPTY_REQUEST (in NetworkClient.kt) which provides no
Content-Type; update the null-body branch and the POST-without-body branch to
create an empty RequestBody with an explicit media type (match the other
branches' MediaType.parse("text/plain; charset=utf-8") usage) instead of raw
EMPTY_REQUEST so the resulting request always has a Content-Type header; adjust
any use of EMPTY_REQUEST in the branches handling ReadableType.Null and the
method.uppercase(...) == "POST" check (and factor into a named
EMPTY_REQUEST_WITH_MEDIA constant if helpful) so behavior is consistent with
String/Boolean/Number branches.

---

Nitpick comments:
In `@android/src/main/java/com/mattermost/networkclient/NetworkClient.kt`:
- Around line 411-431: Replace repeated MediaType.parse() calls by declaring
class-level constants (e.g., MEDIA_TYPE_JSON and MEDIA_TYPE_TEXT) using the
okhttp3 extension toMediaType() and reuse them when creating requestBody in
NetworkClient.kt; add the import okhttp3.MediaType.Companion.toMediaType, define
something like private val MEDIA_TYPE_JSON = "application/json;
charset=utf-8".toMediaType() and private val MEDIA_TYPE_TEXT = "text/plain;
charset=utf-8".toMediaType(), then update the requestBody assignments in the
body-handling switch (the ReadableType.Map/String/Boolean/Number branches) to
pass MEDIA_TYPE_JSON or MEDIA_TYPE_TEXT instead of calling MediaType.parse()
repeatedly.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d0b3c6f5-ab6d-4436-b872-c44559237647

📥 Commits

Reviewing files that changed from the base of the PR and between e25cbaf and cfc500b.

📒 Files selected for processing (1)
  • android/src/main/java/com/mattermost/networkclient/NetworkClient.kt

ddzobov added 2 commits April 14, 2026 15:08
add explicit content-type for empty requests
Refactoring from review comments
@enahum
Copy link
Copy Markdown
Contributor

enahum commented Apr 15, 2026

Thanks for the PR @ddzobov as soon as I have a bit of time, I'll check if this in fact resolves the issue with WAF.

But two things:

  1. iOS seems to be left out, is it because is currently working or because you only focus on Android? If the latter please do test on iOS and update your PR accordingly
  2. Isn't it better to pass the header in the options and include these two types instead of forcing it as this PR does?

@ddzobov
Copy link
Copy Markdown
Author

ddzobov commented Apr 15, 2026

Thanks for the PR @ddzobov as soon as I have a bit of time, I'll check if this in fact resolves the issue with WAF.

But two things:

  1. iOS seems to be left out, is it because is currently working or because you only focus on Android? If the latter please do test on iOS and update your PR accordingly
  2. Isn't it better to pass the header in the options and include these two types instead of forcing it as this PR does?
  1. Yes, iOS code sending application/json now, these users dont have problems at now
  2. As i see from code, header passed in options will have bigger priority, so it will work in both cases

@enahum
Copy link
Copy Markdown
Contributor

enahum commented Apr 15, 2026

Thanks for the PR @ddzobov as soon as I have a bit of time, I'll check if this in fact resolves the issue with WAF.

But two things:

  1. iOS seems to be left out, is it because is currently working or because you only focus on Android? If the latter please do test on iOS and update your PR accordingly
  1. Isn't it better to pass the header in the options and include these two types instead of forcing it as this PR does?
  1. Yes, iOS code sending application/json now, these users dont have problems at now

  2. As i see from code, header passed in options will have bigger priority, so it will work in both cases

So if it works in both cases, I rather not do this here and set the default headers on the mobile app instead and not in the library

@ddzobov
Copy link
Copy Markdown
Author

ddzobov commented Apr 16, 2026

Thanks for the PR @ddzobov as soon as I have a bit of time, I'll check if this in fact resolves the issue with WAF.

But two things:

  1. iOS seems to be left out, is it because is currently working or because you only focus on Android? If the latter please do test on iOS and update your PR accordingly
  1. Isn't it better to pass the header in the options and include these two types instead of forcing it as this PR does?
  1. Yes, iOS code sending application/json now, these users dont have problems at now
  2. As i see from code, header passed in options will have bigger priority, so it will work in both cases

So if it works in both cases, I rather not do this here and set the default headers on the mobile app instead and not in the library

Yes, but current logic in iOS code not sets application/json header explicitly too, currently it determines header implicitly based on serialization type, so with changes in this PR logic will be equal.

If we will set headers on the mobile app, we need to do more complex changes in each request in each class call for request.

@mattermost-build
Copy link
Copy Markdown

This PR has been automatically labelled "stale" because it hasn't had recent activity.
A core team member will check in on the status of the PR to help with questions.
Thank you for your contribution!

@ddzobov
Copy link
Copy Markdown
Author

ddzobov commented Apr 27, 2026

Hello
Any news?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants