public class HttpClientPost {
public HttpClientPost()
{
}
// 返回結果
String strHttpResult = null;
/**
* 发送Http请求到Web站点
*
* @param strURL
* Web站点请求地址
* @param map
* Http请求参数
* @param encode
* 编码格式
* @return string, Web站点响应的字符串
*
*/
public HttpClientPost(final String strURL, Map<String, String> map, final String encode)
{
strHttpResult = null;
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(strURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
if (map != null && !map.isEmpty())
{
for (Map.Entry<String, String> entry : map.entrySet())
{
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
try
{
httppost.setEntity(new UrlEncodedFormEntity(params, encode));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null)
{
InputStream instream = entity.getContent();
try
{
// stream to string
String strResult = InputStream2String(instream);
strHttpResult = strResult;
}
finally
{
instream.close();
}
}
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
/**
* get string from stream
*
* @param inputStream
* @return
* @throws IOException
*/
private String InputStream2String(InputStream inputStream)
{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int i = -1;
String result = null;
try
{
while ((i = inputStream.read()) != -1)
{
outputStream.write(i);
}
result = outputStream.toString();
// result = new String(outputStream.toByteArray(), "gbk");
}
catch (IOException e)
{
e.printStackTrace();
}
return result;
}
/**
* 返回 http 结果
*
* @return
*/
public String getHttpResultString()
{
return strHttpResult;
}
}
HttpClientPost 工具类
最新推荐文章于 2024-10-11 17:29:21 发布