curlconverter / curlconverter

Transpile curl commands into Python, JavaScript and 27 other languages
https://curlconverter.com
MIT License
7.17k stars 867 forks source link

Unnecessary decoding of UTF-8 in Swift (and possibly others) #626

Open rassie opened 3 months ago

rassie commented 3 months ago

Swift generator currently produces this code:

import Foundation

let url = URL(string: "http://example.com/image.png")!

var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
    if let error = error {
        print(error)
    } else if let data = data {
        let str = String(data: data, encoding: .utf8)
        print(str ?? "")
    }
}

task.resume()

In this code, received data is converted to UTF-8, which is only desirable if UTF-8 encoded text data is fetched. This is not always the case -- fetching binary data like images and also text data in different encodings (especially HTML with correctly set encoding) is quite common. Also, no UTF-8 conversion is done in most other examples, so if probably shouldn't be a thing in Swift either.

Possibly, a similar problem lies with Kotlin, which converts the response body to a string:

import java.io.IOException
import okhttp3.OkHttpClient
import okhttp3.Request

val client = OkHttpClient()

val request = Request.Builder()
  .url("http://example.com/image.png")
  .build()

client.newCall(request).execute().use { response ->
  if (!response.isSuccessful) throw IOException("Unexpected code $response")
  response.body!!.string()
}