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;
}
}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下