java http数据传输_java HttpURLConnection 发送文件和字符串信息

java HttpURLConnection 发送文件和字符串信息

以文件的形式传参

/**

* 通过拼接的方式构造请求内容,实现参数传输以及文件传输

*

* @param actionUrl 访问的服务器URL

* @param params 普通参数

* @param files 文件参数

* @return

* @throws IOException

*/

public static void post(String actionUrl, Map params, Map files) throws IOException

{

String BOUNDARY = java.util.UUID.randomUUID().toString();

String PREFIX = "--", LINEND = "\r\n";

String MULTIPART_FROM_DATA = "multipart/form-data";

String CHARSET = "UTF-8";

URL uri = new URL(actionUrl);

HttpURLConnection conn = (HttpURLConnection) uri.openConnection();

conn.setReadTimeout(5 * 1000); // 缓存的最长时间

conn.setDoInput(true);// 允许输入

conn.setDoOutput(true);// 允许输出

conn.setUseCaches(false); // 不允许使用缓存

conn.setRequestMethod("POST");

conn.setRequestProperty("connection", "keep-alive");

conn.setRequestProperty("Charsert", "UTF-8");

conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);

// 首先组拼文本类型的参数

StringBuilder sb = new StringBuilder();

for (Map.Entry entry : params.entrySet())

{

sb.append(PREFIX);

sb.append(BOUNDARY);

sb.append(LINEND);

sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);

sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);

sb.append("Content-Transfer-Encoding: 8bit" + LINEND);

sb.append(LINEND);

sb.append(entry.getValue());

sb.append(LINEND);

}

DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());

outStream.write(sb.toString().getBytes());

InputStream in = null;

// 发送文件数据

if (files != null)

{

for (Map.Entry file : files.entrySet())

{

StringBuilder sb1 = new StringBuilder();

sb1.append(PREFIX);

sb1.append(BOUNDARY);

sb1.append(LINEND);

// name是post中传参的键 filename是文件的名称

sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getKey() + "\"" + LINEND);

sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);

sb1.append(LINEND);

outStream.write(sb1.toString().getBytes());

InputStream is = new FileInputStream(file.getValue());

byte[] buffer = new byte[1024];

int len = 0;

while ((len = is.read(buffer)) != -1)

{

outStream.write(buffer, 0, len);

}

is.close();

outStream.write(LINEND.getBytes());

}

// 请求结束标志

byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();

outStream.write(end_data);

outStream.flush();

// 得到响应码

int res = conn.getResponseCode();

if (res == 200)

{

in = conn.getInputStream();

int ch;

StringBuilder sb2 = new StringBuilder();

while ((ch = in.read()) != -1)

{

sb2.append((char) ch);

}

}

outStream.close();

conn.disconnect();

}

// return in.toString();

}

以数据流的形式传参

public static String postFile(String actionUrl, Map params, Map files)

throws Exception

{

StringBuilder sb2 = null;

String BOUNDARY = java.util.UUID.randomUUID().toString();

String PREFIX = "--", LINEND = "\r\n";

String MULTIPART_FROM_DATA = "multipart/form-data";

String CHARSET = "UTF-8";

URL uri = new URL(actionUrl);

HttpURLConnection conn = (HttpURLConnection) uri.openConnection();

conn.setReadTimeout(6 * 1000); // 缓存的最长时间

conn.setDoInput(true);// 允许输入

conn.setDoOutput(true);// 允许输出

conn.setUseCaches(false); // 不允许使用缓存

conn.setRequestMethod("POST");

conn.setRequestProperty("connection", "keep-alive");

conn.setRequestProperty("Charsert", "UTF-8");

conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);

// 首先组拼文本类型的参数

StringBuilder sb = new StringBuilder();

for (Map.Entry entry : params.entrySet())

{

sb.append(PREFIX);

sb.append(BOUNDARY);

sb.append(LINEND);

sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);

sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);

sb.append("Content-Transfer-Encoding: 8bit" + LINEND);

sb.append(LINEND);

sb.append(entry.getValue());

sb.append(LINEND);

}

DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());

outStream.write(sb.toString().getBytes());

InputStream in = null;

// 发送文件数据

if (files != null)

{

for (Map.Entry file : files.entrySet())

{

StringBuilder sb1 = new StringBuilder();

sb1.append(PREFIX);

sb1.append(BOUNDARY);

sb1.append(LINEND);

sb1.append("Content-Disposition: form-data; name=\"pic\"; filename=\"" + file.getKey() + "\"" + LINEND);

sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);

sb1.append(LINEND);

outStream.write(sb1.toString().getBytes());

// InputStream is = new FileInputStream(file.getValue());

// byte[] buffer = new byte[1024];

// int len = 0;

// while ((len = is.read(buffer)) != -1)

// {

// outStream.write(buffer, 0, len);

// }

// is.close();

outStream.write(file.getValue());

outStream.write(LINEND.getBytes());

}

// 请求结束标志

byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();

outStream.write(end_data);

outStream.flush();

// 得到响应码

int res = conn.getResponseCode();

if (res == 200)

{

in = conn.getInputStream();

int ch;

sb2 = new StringBuilder();

while ((ch = in.read()) != -1)

{

sb2.append((char) ch);

}

System.out.println(sb2.toString());

}

outStream.close();

conn.disconnect();

// 解析服务器返回来的数据

return ParseJson.getEditMadIconResult(sb2.toString());

}

else

{

return "Update icon Fail";

}

// return in.toString();

}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 要实现通过 HTTP 协议输本地图片,你需要按照以下步骤进行操作: 1. 使用 Java 中的 File 类读取本地图片文件并转换为字节数组。 ```java File file = new File("path/to/image.jpg"); byte[] imageData = Files.readAllBytes(file.toPath()); ``` 2. 创建 HttpURLConnection 对象,并设置请求方法为 POST。 ```java URL url = new URL("http://example.com/upload"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); ``` 3. 设置请求信息,包括 Content-Type 和文件名等。 ```java conn.setRequestProperty("Content-Type", "image/jpeg"); conn.setRequestProperty("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); ``` 4. 开启输出流并将字节数组写入到输出流中。 ```java conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); os.write(imageData); os.flush(); os.close(); ``` 5. 发送请求并获取响应结果。 ```java int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // 处理响应结果 InputStream is = conn.getInputStream(); // ... } ``` 完整代码示例: ```java import java.io.File; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.file.Files; public class HttpImageUploader { public static void main(String[] args) { try { // 读取本地图片文件并转换为字节数组 File file = new File("path/to/image.jpg"); byte[] imageData = Files.readAllBytes(file.toPath()); // 创建 HttpURLConnection 对象,并设置请求方法为 POST URL url = new URL("http://example.com/upload"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); // 设置请求信息,包括 Content-Type 和文件名等 conn.setRequestProperty("Content-Type", "image/jpeg"); conn.setRequestProperty("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); // 开启输出流并将字节数组写入到输出流中 conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); os.write(imageData); os.flush(); os.close(); // 发送请求并获取响应结果 int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // 处理响应结果 InputStream is = conn.getInputStream(); // ... } } catch (Exception e) { e.printStackTrace(); } } } ``` ### 回答2: 在Java中实现通过HTTP输本地图片,可以通过以下步骤进行实现: 1. 使用Java的IO流读取本地图片文件,可以使用`FileInputStream`类来读取文件。首先,我们需要使用文件路径来创建一个`File`对象,然后使用`FileInputStream`来读取文件内容并保存到一个字节数组中。 2. 创建一个`URL`对象,指定要上图片的目标URL地址。可以使用`URL`类的构造函数入目标URL地址字符串来创建它。 3. 打开一个HTTP连接,可以使用`URLConnection`类的`openConnection()`方法打开一个连接,并强制转换为`HttpURLConnection`对象,因为HTTP输需要使用这个对象来设置请求方法、请求头等。 4. 设置HTTP连接的请求方法为POST,并设置一些必要的请求信息。例如,可以将请求头字段"Content-Type"设置为"multipart/form-data",表示输的内容是多部分的。 5. 创建一个输出流,将字节数组作为请求发送给目标URL。可以使用`HttpURLConnection`对象的`getOutputStream()`方法获取输出流,并使用`write()`方法写入字节数组。 6. 获取服务器响应,可以使用`HttpURLConnection`对象的`getInputStream()`方法获取服务器响应的输入流,然后读取响应内容。 7. 最后,记得关闭输入流和输出流,并断开HTTP连接。 总结起来,通过以上步骤,我们可以实现通过HTTP输本地图片。需要注意的是,为了避免出现内存泄漏和资源未释放的情况,应该适时地关闭输入流和输出流,并及时断开HTTP连接。 ### 回答3: 要使用Java实现通过HTTP输本地图片,可以按照以下步骤进行: 1. 首先,需要使用Java文件输入流将本地的图片文件读取到内存中。可以使用`FileInputStream`类来实现,将文件路径作为参数递给该类的构造函数。 ```java FileInputStream fileInputStream = new FileInputStream("图片文件路径"); ``` 2. 接下来,需要创建一个URL对象,指定HTTP的目标地址。可以使用`URL`类来实现,将目标地址作为参数递给该类的构造函数。 ```java URL url = new URL("HTTP目标地址"); ``` 3. 然后,需要创建一个HTTP连接对象,可以使用`HttpURLConnection`类来实现。通过调用`openConnection()`方法创建该对象,并将URL对象作为参数递给该方法。 ```java HttpURLConnection connection = (HttpURLConnection) url.openConnection(); ``` 4. 设置HTTP请求方法为POST,并启用输出流和输入流。设置请求头的Content-Type为multipart/form-data,以支持文件。同时设置连接超时和读取超时的时间。 ```java connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=----Boundary"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); ``` 5. 获取输出流对象,并将图片数据写入输出流。 ```java OutputStream outputStream = connection.getOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = fileInputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } ``` 6. 获取服务器返回的输入流,并对其进行相应的处理。 ```java InputStream inputStream = connection.getInputStream(); // 对返回的数据进行处理 ``` 7. 最后,关闭输入流、输出流和连接。 ```java fileInputStream.close(); outputStream.close(); connection.disconnect(); ``` 以上就是通过Java实现HTTP输本地图片的基本步骤。根据具体的需求,还可以添加其他功能,比如设置请求头中的其他参数、添加身份验证等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值