我正在尝试制作一个程序,将图像上传到接受多部分文件上传的Web服务器。
更具体地说,我想向http://iqs.me发送一个包含在变量“pic”中的文件的HTTP POST请求。
我已经尝试了很多次,但我不知道是否接近成功。最难的部分似乎是获取HttpURLConnection以进行POST类型的请求。我收到的响应看起来像是GET请求。
(我想做到这一点,而不使用任何第三方库)
更新:下面是无法工作的代码(没有错误,但似乎没有执行POST)。
更具体地说,我想向http://iqs.me发送一个包含在变量“pic”中的文件的HTTP POST请求。
我已经尝试了很多次,但我不知道是否接近成功。最难的部分似乎是获取HttpURLConnection以进行POST类型的请求。我收到的响应看起来像是GET请求。
(我想做到这一点,而不使用任何第三方库)
更新:下面是无法工作的代码(没有错误,但似乎没有执行POST)。
HttpURLConnection conn = null;
BufferedReader br = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
InputStream is = null;
OutputStream os = null;
boolean ret = false;
String StrMessage = "";
String exsistingFileName = "myScreenShot.png";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "http://iqs.local.com/index.php";
try{
FileInputStream fileInputStream = new FileInputStream( new File(exsistingFileName) );
URL url = new URL(urlString);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"pic\";" + " filename=\"" + exsistingFileName +"\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0){
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
fileInputStream.close();
dos.flush();
dos.close();
}catch (MalformedURLException ex){
System.out.println("Error:"+ex);
}catch (IOException ioe){
System.out.println("Error:"+ioe);
}
try{
inStream = new DataInputStream ( conn.getInputStream() );
String str;
while (( str = inStream.readLine()) != null){
System.out.println(str);
}
inStream.close();
}catch (IOException ioex){
System.out.println("Error: "+ioex);
}