BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
时间: 2024-03-27 22:31:48 浏览: 221
以下是使用BufferedReader类创建一个读取器的示例代码:
```java
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) {
InputStream input = // 获取输入流
BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
// 使用reader读取数据
// ...
}
}
```
这段代码创建了一个BufferedReader对象,它使用UTF-8字符集从输入流中读取数据。你可以使用这个reader对象来读取输入流中的数据。
相关问题
private void handle(InputStream input, OutputStream output) throws IOException { System.out.println("Process new http request..."); var reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)); var writer = new BufferedWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8)); // 读取HTTP请求: boolean requestOk = false; String first = reader.readLine(); if (first.startsWith("GET / HTTP/1.")) { requestOk = true; } for (;;) { String header = reader.readLine(); if (header.isEmpty()) { // 读取到空行时, HTTP Header读取完毕 break; } System.out.println(header); } System.out.println(requestOk ? "Response OK" : "Response Error"); if (!requestOk) { // 发送错误响应: writer.write("HTTP/1.0 404 Not Found\r\n"); writer.write("Content-Length: 0\r\n"); writer.write("\r\n"); writer.flush(); } else { // 发送成功响应: String data = "<html><body><h1>Hello, world!</h1></body></html>"; int length = data.getBytes(StandardCharsets.UTF_8).length; writer.write("HTTP/1.0 200 OK\r\n"); writer.write("Connection: close\r\n"); writer.write("Content-Type: text/html\r\n"); writer.write("Content-Length: " + length + "\r\n"); writer.write("\r\n"); // 空行标识Header和Body的分隔 writer.write(data); writer.flush(); } }
这段代码是一个简单的 HTTP 服务器的处理方法。它通过输入流和输出流处理 HTTP 请求和响应。首先,它从输入流中读取 HTTP 请求的第一行,然后通过循环读取 HTTP 头部信息,直到读取到空行。如果请求的路径是根路径,则设置请求为有效。如果请求无效,它将发送一个 404 错误响应,否则将发送一个包含“Hello, world!”的 HTML 响应。此代码使用 UTF-8 编码。
帮我翻译为java代码 var http = (HttpWebRequest)WebRequest.Create(url); http.Accept = "*/*"; http.Method = "POST"; http.ContentType = "application/json; charset=utf-8"; TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); var currentTimeSeconds = Convert.ToInt64(ts.TotalSeconds); var signature = AESHelper.AesLocal(AppId + ApiId + currentTimeSeconds, AppKey); http.Headers["signature"] = signature; http.Headers["apiname"] = ApiId; http.Headers["appid"] = AppId; http.Headers["appkey"] = AppKey; http.ContentType = "application/json;charset=utf-8"; http.UserAgent = "PostmanRuntime/7.26.8"; Random rd = new Random(); var rdNum = rd.Next(100000, 1000000); var signStr = thirdId + "/n" + rdNum + "/n" + currentTimeSeconds + "/n" + key+"/n"; var sign = Md5Helper.Encrypt32(Base64Helper.EncodeBase64(Encoding.UTF8,signStr)); http.Headers["thirdId"] = thirdId; http.Headers["nonceStr"] = rdNum.ToString(); http.Headers["time"] = currentTimeSeconds.ToString(); http.Headers["sign"] = sign; byte[] bs = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data)); using (var reqStream = http.GetRequestStream()) { reqStream.Write(bs, 0, bs.Length); } using (var wr = http.GetResponse()) { using (var reader = new StreamReader(wr.GetResponseStream(), Encoding.UTF8)) { var result = reader.ReadToEnd(); var json = (JObject)JsonConvert.DeserializeObject(result); if (json["success"] == null || json["success"].ToString().ToLower() != "true") { Logger.Log(MethodBase.GetCurrentMethod().Name, GetType().Name, 1, "获取广告点位失败:" + JsonConvert.SerializeObject(param)+"////"+result, LogLevel.Error); } return result; } }
下面是Java代码的翻译:
```
URL url = new URL(urlStr);
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setRequestMethod("POST");
http.setDoOutput(true);
http.setDoInput(true);
http.setUseCaches(false);
http.setRequestProperty("Accept", "*/*");
http.setRequestProperty("Content-Type", "application/json; charset=utf-8");
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
long currentTimeSeconds = Convert.ToInt64(ts.TotalSeconds);
String signature = AESHelper.AesLocal(AppId + ApiId + currentTimeSeconds, AppKey);
http.setRequestProperty("signature", signature);
http.setRequestProperty("apiname", ApiId);
http.setRequestProperty("appid", AppId);
http.setRequestProperty("appkey", AppKey);
http.setRequestProperty("User-Agent", "PostmanRuntime/7.26.8");
Random rd = new Random();
int rdNum = rd.nextInt(1000000) + 100000;
String signStr = thirdId + "/n" + rdNum + "/n" + currentTimeSeconds + "/n" + key+"/n";
String sign = Md5Helper.Encrypt32(Base64Helper.EncodeBase64(Encoding.UTF8,signStr));
http.setRequestProperty("thirdId", thirdId);
http.setRequestProperty("nonceStr", String.valueOf(rdNum));
http.setRequestProperty("time", String.valueOf(currentTimeSeconds));
http.setRequestProperty("sign", sign);
byte[] postData = data.toString().getBytes(StandardCharsets.UTF_8);
DataOutputStream wr = new DataOutputStream(http.getOutputStream());
wr.write(postData);
wr.flush();
wr.close();
int responseCode = http.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String result = response.toString();
JSONObject json = new JSONObject(result);
if (json.isNull("success") || !json.getString("success").toLowerCase().equals("true")) {
Logger.Log(MethodBase.GetCurrentMethod().getName(), getClass().getName(), 1, "获取广告点位失败:" + param.toString() + "////" + result, LogLevel.Error);
}
return result;
} else {
throw new Exception("HTTP请求失败,状态码:" + responseCode);
}
```
阅读全文