java请求外部接口参数为字节流和字符串
时间: 2024-06-09 19:05:37 浏览: 70
java字节流和字符流
Java请求外部接口可以使用HttpURLConnection或者HttpClient来实现。下面是使用HttpURLConnection发送请求的示例代码:
```java
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpUrlConnectionExample {
public static void main(String[] args) throws Exception {
String url = "http://example.com/api";
String jsonString = "{\"key\":\"value\"}";
byte[] bytes = {0x01, 0x02, 0x03};
String response = sendPostRequest(url, jsonString, bytes);
System.out.println(response);
}
private static String sendPostRequest(String urlString, String jsonString, byte[] bytes) throws IOException {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(jsonString);
out.flush();
out.close();
InputStream inputStream = conn.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
}
```
在这个例子中,我们使用了HttpURLConnection来发送POST请求。我们设置了请求头Content-Type为application/json,然后使用DataOutputStream将json字符串写入请求体。字节流也可以使用同样的方式写入请求体。最后,我们从连接的输入流中读取响应内容。
阅读全文