gpt4 book ai didi

java - 为什么在http请求中编码?

转载 作者:可可西里 更新时间:2023-11-01 17:28:05 26 4
gpt4 key购买 nike

我正在尝试在 Java 上使用 http 协议(protocol)从服务器学习请求和检索数据这是我在 Oracle>教程>网络上找到的代码(代码粘贴在问题的底部)

问题 1: out.write("string="+ stringToReverse);为什么 "string="没有被编码?像 stringToReverse 变量

String stringToReverse = URLEncoder.encode(args[1], "UTF-8");

问题 2:下面有两段代码,一段来自 oracle 代码,另一段来自 android studio tuts

oracle tuts 中的代码

BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

android tuts 代码

inputStream = urlConnection.getInputStream();    
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);

为什么 Oracle 代码中缺少 Charset.forName("UTF-8")?


注意:从基础开始解释非常有用:)

import java.io.*;
import java.net.*;

public class Reverse {
public static void main(String[] args) throws Exception {

if (args.length != 2) {
System.err.println("Usage: java Reverse "
+ "http://<location of your servlet/script>"
+ " string_to_reverse");
System.exit(1);
}

String stringToReverse = URLEncoder.encode(args[1], "UTF-8");

URL url = new URL(args[0]);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);

OutputStreamWriter out = new OutputStreamWriter(
connection.getOutputStream());
out.write("string=" + stringToReverse);
out.close();

BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
in.close();
}
}

最佳答案

问题 1:

无需对“string=”进行编码(因为它不包含任何特殊字符,如 https://docs.oracle.com/javase/6/docs/api/java/net/URLEncoder.html 中所述)

问题 2:

以下示例中的字符集未明确定义:

BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

因此使用默认字符集(可能不是 UTF-8)

Every instance of the Java virtual machine has a default charset, which may or may not be one of the standard charsets. The default charset is determined during virtual-machine startup and typically depends upon the locale and charset being used by the underlying operating system. (https://docs.oracle.com/javase/7/docs/api/java/nio/charset/Charset.html)

关于java - 为什么在http请求中编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42901204/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com