HttpClient Post 二进制/字节流/byte[]实例代码
HttpClient Post 二进制/字节流/byte[]实例代码
HttpClient 3.x
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) && (contentType.length() > 0)) method.setRequestHeader("Content-type" , contentType); method.setRequestEntity(new ByteArrayRequestEntity(bytes)); int HttpCode = m_HttpClient.executeMethod(method); if (HttpCode != HttpStatus.SC_OK) throw new IOException("Invalid HttpStatus: " + HttpCode); InputStream respStream = method.getResponseBodyAsStream(); int respBodySize = respStream.available(); if (respBodySize <= 0) throw new IOException("Invalid respBodySize: " + respBodySize); byte[] respBuffer = new byte[respBodySize]; if (respStream.read(respBuffer) != respBodySize) throw new IOException("Read respBody Error"); return respBuffer; } public String postXml(String str) throws IOException { byte[] reqBuffer = str.getBytes(Charset.forName("UTF-8")); byte[] respBuffer = post(reqBuffer, "application/xml; charset=UTF-8"); String resp = new String(respBuffer, Charset.forName("UTF-8")); return resp; } }
HttpClient 4.x
public class HttpHelper { CloseableHttpClient m_HttpClient; public HttpHelper() { m_HttpClient = HttpClients.createDefault(); } // send bytes and recv bytes public byte[] post(String url, byte[] bytes, String contentType) throws IOException { HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new ByteArrayEntity(bytes)); if (contentType != null) httpPost.setHeader("Content-type", contentType); CloseableHttpResponse httpResponse = m_HttpClient.execute(httpPost); try { HttpEntity entityResponse = httpResponse.getEntity(); int contentLength = (int) entityResponse.getContentLength(); if (contentLength <= 0) throw new IOException("No response"); byte[] respBuffer = new byte[contentLength]; if (entityResponse.getContent().read(respBuffer) != respBuffer.length) throw new IOException("Read response buffer error"); return respBuffer; } finally { httpResponse.close(); } } 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 = str.getBytes(Charset.forName("UTF-8")); byte[] respBuffer = post(url, reqBuffer, "application/xml; charset=UTF-8"); String resp = new String(respBuffer, Charset.forName("UTF-8")); return resp; } }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
相关推荐
jiangtie 2020-08-15
长安长夜Saint 2020-06-14
kerson 2020-05-11
milidou 2020-01-11
paopao00 2020-01-09
Joymine 2020-01-06
疯仔嵌入式 2011-04-10
hehezhou 2012-02-10
wordmhg 2019-10-24
Hashxu 2012-04-21
大伟爱自由 2012-02-10
benico 2010-01-31
MySQLfred 2019-07-01
hanniuniu 2019-06-27
frank0 2010-03-30
Andyshrk 2018-08-23
一只菜鸡 2014-05-28
dalian 2010-03-15
Stephenzsky 2019-05-27