kotlin 从Java 11 HttpClient到okhttp的转换是否正确?

oxiaedzo  于 2022-11-16  发布在  Kotlin
关注(0)|答案(1)|浏览(144)

我想要完成的任务是从POST方法中获取PDF文件并将其显示给用户。
我尝试过的方法:
我有一个Java示例,它使用Java 11 HttpClient API发送POST请求,将ZPL字符串从labelary转换为PDF文件:

var zpl = "^xa^cfa,50^fo100,100^fdHello World^fs^xz";

// adjust print density (8dpmm), label width (4 inches), label height (6 inches), and label index (0) as necessary
var uri = URI.create("http://api.labelary.com/v1/printers/8dpmm/labels/4x6/0/");
var request = HttpRequest.newBuilder(uri)
    .header("Accept", "application/pdf") // omit this line to get PNG images back
    .POST(BodyPublishers.ofString(zpl))
    .build();
var client = HttpClient.newHttpClient();
var response = client.send(request, BodyHandlers.ofByteArray());
var body = response.body();

if (response.statusCode() == 200) {
    var file = new File("label.pdf"); // change file name for PNG images
    Files.write(file.toPath(), body);
} else {
    var errorMessage = new String(body, StandardCharsets.UTF_8);
    System.out.println(errorMessage);
}

据我所知,这段代码是不可能与Android。所以我已经尝试了它与Squareup okhttp库如下:

fun fetch(completion: (InputStream?) -> Unit) {
    val url = "https://api.labelary.com/v1/printers/8dpmm/labels/4x6/0/"
    val postBody = "^xa^cfa,50^fo100,100^fdHello World^fs^xz"
    val text = MediaType.parse("text/plain;charset=utf-8")
    val body = RequestBody.create(text, postBody)
    val labelFetch = OkHttpClient()
    val request = Request.Builder()
        .header("Accept", "application/pdf")
        .url(url)
        .post(body)
        .build()

    labelFetch.newCall(request).enqueue(object : Callback {
        override fun onFailure(request: Request?, e: IOException?) {

        }

        override fun onResponse(response: Response?) {
            val pdfData = response?.body()?.byteStream()
            completion(pdfData)
        }
    })
}

稍后,我得到InputStream,如果它不为空,我将使用pdfViewer显示它,但我得到如下错误:
java.io.IOException:文件不是PDF格式或已损坏

x7yiwoj4

x7yiwoj41#

它看起来像这样,它会工作,但我想知道一个更好的解决方案

fun fetch(completion: (InputStream?) -> Unit) {
    val url = "http://api.labelary.com/v1/printers/8dpmm/labels/4x6/0/^xa^cfa,50^fo100,100^fdHello World^fs^xz"
    val labelFetch = OkHttpClient()
    val request = Request.Builder()
        .header("Accept", "application/pdf")
        .url(url)
        .build()

    labelFetch.newCall(request).enqueue(object : Callback {
        override fun onFailure(request: Request?, e: IOException?) {
        }

        override fun onResponse(response: Response?) {
            val pdfData = response?.body()?.byteStream()
            completion(pdfData)
        }
    })

相关问题