HttpClient Post Binary/Byte Stream/byte[] Instance Code
HttpClient
public class HttpHelper { String m_url; HttpClient m_HttpClient; public HttpHelper(String url) { m_url = url; m_HttpClient = new HttpClient(); } public byte[] post(byte[] bytes, String contentType) throws IOException { PostMethod method = new PostMethod(m_url); if ((contentType != null) && (() > 0)) ("Content-type" , contentType); (new ByteArrayRequestEntity(bytes)); int HttpCode = m_HttpClient.executeMethod(method); if (HttpCode != HttpStatus.SC_OK) throw new IOException("Invalid HttpStatus: " + HttpCode); InputStream respStream = (); int respBodySize = (); if (respBodySize <= 0) throw new IOException("Invalid respBodySize: " + respBodySize); byte[] respBuffer = new byte[respBodySize]; if ((respBuffer) != respBodySize) throw new IOException("Read respBody Error"); return respBuffer; } public String postXml(String str) throws IOException { byte[] reqBuffer = (("UTF-8")); byte[] respBuffer = post(reqBuffer, "application/xml; charset=UTF-8"); String resp = new String(respBuffer, ("UTF-8")); return resp; } }
HttpClient
public class HttpHelper { CloseableHttpClient m_HttpClient; public HttpHelper() { m_HttpClient = (); } // send bytes and recv bytes public byte[] post(String url, byte[] bytes, String contentType) throws IOException { HttpPost httpPost = new HttpPost(url); (new ByteArrayEntity(bytes)); if (contentType != null) ("Content-type", contentType); CloseableHttpResponse httpResponse = m_HttpClient.execute(httpPost); try { HttpEntity entityResponse = (); int contentLength = (int) (); if (contentLength <= 0) throw new IOException("No response"); byte[] respBuffer = new byte[contentLength]; if (().read(respBuffer) != ) throw new IOException("Read response buffer error"); return respBuffer; } finally { (); } } public byte[] post(String url, byte[] bytes) throws IOException { return post(url, bytes, null); } public String postXml(String url, String str) throws IOException { byte[] reqBuffer = (("UTF-8")); byte[] respBuffer = post(url, reqBuffer, "application/xml; charset=UTF-8"); String resp = new String(respBuffer, ("UTF-8")); return resp; } }
Thank you for reading, I hope it can help you. Thank you for your support for this site!