使用java将文本和图像发送到php
这是我关于stackoverflow的第一个问题,所以如果你对我提出/解释的方式有任何意见,我很乐意接受任何建议
这就是:
我想向服务器上的php脚本发送文本和图像。我可以成功地将两者分开发送,但不能一起发送。到目前为止,我用这个来表示字符串:
String dataSend = URLEncoder.encode("User","UTF-8") +"="+URLEncoder.encode(username,"UTF-8");
URL url = new URL(urlCopyImage);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(dataSend);
out.close();
对于我使用的图像:
URL url = new URL(urlCopyImage);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
ImageIO.write(image,"PNG", connection.getOutputStream());
我能把这两者结合起来吗
在php脚本中,我仅使用$_POST
来接收字符串,并使用以下图像:
$incomingData = file_get_contents('php://input');
欢迎任何提示
作为记录,我使用php文件在服务器上创建了一个包含此图像的文件。用户名用于指定目录
编辑:
多亏了你的回答,我才得以成功,尽管我还不太明白
MultipartEntity multipart = new MultipartEntity();
multipart.addPart("User", new StringBody(username));
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(image, "png", os);
InputStream is = new ByteArrayInputStream(os.toByteArray());
ContentBody cb = new InputStreamBody(is, "something.png");
multipart.addPart("Image", cb);
HttpPost post = new HttpPost(urlCopyImage);
post.setEntity(multipart);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
我正在将一个inputstreambody传递给contentbody,它从ImageIO获取ByTestStream。太好了。但是我不知道inputstreambody的第二个参数应该做什么。虽然这样做有效,但感觉不太对
顺便说一句,这是php代码:
$user = $_POST['User'];
copy($_FILES['Image']['tmp_name'],$filename);
如果有人能解释一下我到底在做什么,我将不胜感激。谢谢你的帮助
# 1 楼答案
使用ApacheHTTP客户端使用mime类型的多部分/表单数据发出POST请求,并为二进制数据和文本添加部分
在PHP端,您可以通过$\u文件读取该文件
看看我不久前写的这篇博文http://zybnet.com/java-http-client-and-post-requests/