HttpClientPost 工具类

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;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值