是否可以将字符串和图像同时发布到网络服务器?

时间:2015-04-22 09:37:17

标签: android

有一个string变量和一张来自photo意图的图片cameradirectory的{​​{1}}位置已知。我想同时将photo变量的HTTP poststring照片发送到网络服务器。那可能吗 ?如果是的话,该怎么做?

2 个答案:

答案 0 :(得分:4)

根据我的理解,您需要在单个POST请求中向您的网络服务器发送图像和字符串。以下是您的工作方式。

首先需要对图像进行Base64编码。

converting your image into a byte array开始:

InputStream image = new FileInputStream(<path_to_image>);
byte[] buff = new byte[8192];
int readBytes;
ByteArrayOutputStream byteArrOS = new ByteArrayOutputStream(); 
try {
    while ( (readBytes = inputStream.read(buff) ) != -1) {
    byteArrOS.write(buff, 0, readBytes);
}
} catch (IOException e) {
    e.printStackTrace();
}
byte[] b = byteArrOS.toByteArray();

然后将其转换为Base64:

String bsfEncodedImage = Base64.encodeToString(b, Base64.DEFAULT);

然后用字符串构建一个查询,结果Base64都用URLEncoder编码,&#34; utf-8&#34;:

strImgQuery = "str="+URLEncoder.encode(<string_data>, "utf-8")+"&image="+URLEncoder.encode(bsfEncodedImage, "utf-8");

宣布新的URL

URL postUrl = new URL("http://<IP>/postreq");

打开连接:

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

将输出设置为&#34; true&#34; (需要POST请求但不需要GET):

conn.setDoOutput(true);

将请求方法设置为POST:

conn.setRequestMethod("POST");

超时:

conn.setReadTimeout(1e4);

将输出缓冲到输出流并刷新/运行:

Writer buffWriter = new OutputStreamWriter(conn.getOutputStream());
buffWrite.write(strImgQuery);
buffWriter.flush();
buffWriter.close();

在服务器端,您将获得strimage POST参数,这取决于您的服务器实施。

请注意,您的网址必须遵循URL Specification,否则您将获得MalformedURLException。如果是这种情况,请务必检查完全的问题。例如,如果您使用不存在的ttp&#34;协议&#34;而不是http您的异常将如下所示:

java.net.MalformedURLException: unknown protocol: ttp
    at java.net.URL.<init>(URL.java:592)
    at java.net.URL.<init>(URL.java:482)
    at java.net.URL.<init>(URL.java:431)
    at com.pheromix.core.lang.NumberFormatExceptionExample.MalformedURLExceptionExample.sendGetRequest(MalformedURLExceptionExample.java:28)
    at com.pheromix.core.lang.NumberFormatExceptionExample.MalformedURLExceptionExample.main(MalformedURLExceptionExample.java:17)

此外,这是一个同步操作,并在UI线程上运行。它可能代价高昂,或者可能不依赖于您已经运行的其他操作以及POST数据的大小。如果出现问题,run the job on another thread

答案 1 :(得分:-1)

您可以使用URLEncoder

String strUrl = "http://192.168.1.9/impots/" +URLEncoder.encode("outil.php?action=OutilImporterDonneesMobile", "utf-8");
URL url = new URL(strUrl);