UAC
833 постов
Карма: 27
#1 27 января 2012 в 22:12
Есть следующий код (клиент). Он выполняет отсылку большого файла на сервер. Код рабочий. Единственное что мне в нем не нравиться - факт того что openConnection() должен вызываеться в цикле, а disconnect() - за рамками цикла. С помощью такого кода я пытаюсь сделать не совсем коректную вещь - multiple POST-запросы через HttpURLConnection. Из документации стало ясным что &quot;Each HttpURLConnection instance is used to make a single request but the underlying network connection to the HTTP server may be transparently shared by other instances&quot;.&nbsp; Потом наткнулся на вот такой пост на форуме (источник): &quot;URLConnection по возможности использует одно физическое соединение при повторных обращениях к одному хосту (если не применять disconnect() после каждого запроса), хотя обьект URLConnection надо каждый раз создавать новый. Это, наверное, вводит в заблуждение.&quot; И вот стою на асфальте я в лыжи обутый, то ли лыжи не едут, то ли я еб...нутый... Неясно - нормальный ли это порядок вещей и правильно ли построен код. Поясните пожалуйста, если кто-то хорошо знаком с HTTP-протоколом и Java. <br /><br />package myPkg;<br /><br />import java.io.*;<br />import java.net.HttpURLConnection;<br />import java.net.URL;<br />import java.nio.file.Files;<br />import java.nio.file.Path;<br />import java.nio.file.Paths;<br /><br />public class MyLogic {<br /><br />&nbsp; &nbsp; public MyLogic() {<br />&nbsp; &nbsp; }<br /><br />&nbsp; &nbsp; private String defaultURL = &quot;http://localhost:8080/myapp/test&quot;;<br /><br />&nbsp; &nbsp; public String sendPostRequest() {<br /><br />&nbsp; &nbsp; &nbsp; &nbsp; OutputStream os = null;<br />&nbsp; &nbsp; &nbsp; &nbsp; StringBuffer messagebuffer = new StringBuffer();<br />&nbsp; &nbsp; &nbsp; &nbsp; HttpURLConnection huc = null;<br />&nbsp; &nbsp; &nbsp; &nbsp; DataInputStream dis;<br />&nbsp; &nbsp; &nbsp; &nbsp; InputStream in = null;<br />&nbsp; &nbsp; &nbsp; &nbsp; Path path;<br />&nbsp; &nbsp; &nbsp; &nbsp; byte&#91;] buf = new byte[32 * 1024];<br />&nbsp; &nbsp; &nbsp; &nbsp; int bytesRead = 0;<br /><br />&nbsp; &nbsp; &nbsp; &nbsp; try {<br /><br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; path = Paths.get(&quot;D:\\downloads\\testfile&quot;); <br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; in = Files.newInputStream(path);<br /><br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; URL u = new URL(defaultURL);<br /><br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int i = 0;<br /><br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; while ((bytesRead = in.read(buf)) != -1) {<br /><br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; huc = (HttpURLConnection) u.openConnection();<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; huc.setRequestMethod(&quot;POST&quot;);<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; huc.setDoOutput(true);<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; huc.setDoInput(true);<br /><br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; os = huc.getOutputStream();<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; os.write(buf, 0, bytesRead);<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; os.flush();<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; os.close();<br /><br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(i++ + &quot; &quot; + bytesRead);<br /><br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dis = new DataInputStream(huc.getInputStream()); <br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int ch;<br /><br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; long len = huc.getContentLength();<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (len != -1) {<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int k = 0; k &lt; len; k++)<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if ((ch = dis.read()) != -1)<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; messagebuffer.append((char) ch);<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else {<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; while ((ch = dis.read()) != -1)<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; messagebuffer.append((char) ch);<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dis.close(); <br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int statusCode = huc.getResponseCode();<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String message = huc.getResponseMessage();<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; messagebuffer.append(&quot;status code=&quot; + statusCode + &quot;\n&quot;);<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; messagebuffer.append(&quot;response message=&quot; + message + &quot;\n&quot;);<br /><br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Thread.sleep(16);<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }<br /><br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; huc.disconnect();<br /><br />&nbsp; &nbsp; &nbsp; &nbsp; } catch (Exception ex) {<br /><br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; messagebuffer.append(ex.toString());<br /><br />&nbsp; &nbsp; &nbsp; &nbsp; } finally {<br /><br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try {<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (in != null)<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; in.close();<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } catch (IOException ignored) {<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try {<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (os != null)<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; os.close();<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } catch (IOException ignored) {<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try {<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (huc != null)<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; huc.disconnect();<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } catch (Exception ignored) {<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }<br /><br />&nbsp; &nbsp; &nbsp; &nbsp; }<br />&nbsp; &nbsp; &nbsp; &nbsp; return messagebuffer.toString();<br />&nbsp; &nbsp; }<br />}