HttpClient Post 二进制/字节流/byte[]实例代码
HttpClientPost二进制/字节流/byte[]实例代码
HttpClient3.x
publicclassHttpHelper{
Stringm_url;
HttpClientm_HttpClient;
publicHttpHelper(Stringurl){
m_url=url;
m_HttpClient=newHttpClient();
}
publicbyte[]post(byte[]bytes,StringcontentType)throwsIOException{
PostMethodmethod=newPostMethod(m_url);
if((contentType!=null)&&(contentType.length()>0))
method.setRequestHeader("Content-type",contentType);
method.setRequestEntity(newByteArrayRequestEntity(bytes));
intHttpCode=m_HttpClient.executeMethod(method);
if(HttpCode!=HttpStatus.SC_OK)
thrownewIOException("InvalidHttpStatus:"+HttpCode);
InputStreamrespStream=method.getResponseBodyAsStream();
intrespBodySize=respStream.available();
if(respBodySize<=0)
thrownewIOException("InvalidrespBodySize:"+respBodySize);
byte[]respBuffer=newbyte[respBodySize];
if(respStream.read(respBuffer)!=respBodySize)
thrownewIOException("ReadrespBodyError");
returnrespBuffer;
}
publicStringpostXml(Stringstr)throwsIOException{
byte[]reqBuffer=str.getBytes(Charset.forName("UTF-8"));
byte[]respBuffer=post(reqBuffer,"application/xml;charset=UTF-8");
Stringresp=newString(respBuffer,Charset.forName("UTF-8"));
returnresp;
}
}
HttpClient4.x
publicclassHttpHelper{
CloseableHttpClientm_HttpClient;
publicHttpHelper(){
m_HttpClient=HttpClients.createDefault();
}
//sendbytesandrecvbytes
publicbyte[]post(Stringurl,byte[]bytes,StringcontentType)throwsIOException{
HttpPosthttpPost=newHttpPost(url);
httpPost.setEntity(newByteArrayEntity(bytes));
if(contentType!=null)
httpPost.setHeader("Content-type",contentType);
CloseableHttpResponsehttpResponse=m_HttpClient.execute(httpPost);
try{
HttpEntityentityResponse=httpResponse.getEntity();
intcontentLength=(int)entityResponse.getContentLength();
if(contentLength<=0)
thrownewIOException("Noresponse");
byte[]respBuffer=newbyte[contentLength];
if(entityResponse.getContent().read(respBuffer)!=respBuffer.length)
thrownewIOException("Readresponsebuffererror");
returnrespBuffer;
}finally{
httpResponse.close();
}
}
publicbyte[]post(Stringurl,byte[]bytes)throwsIOException{
returnpost(url,bytes,null);
}
publicStringpostXml(Stringurl,Stringstr)throwsIOException{
byte[]reqBuffer=str.getBytes(Charset.forName("UTF-8"));
byte[]respBuffer=post(url,reqBuffer,"application/xml;charset=UTF-8");
Stringresp=newString(respBuffer,Charset.forName("UTF-8"));
returnresp;
}
}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!