首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 操作系统 >

HttpClient post跟get提交http

2013-07-26 
HttpClient post和get提交http/*** Url Post请求* @param url url地址* @param charset 字符编码* @param

HttpClient post和get提交http
/** * Url Post请求 * @param url url地址 * @param charset 字符编码 * @param params 参数 * @return */ public String doPost(String url, String charset,NameValuePair[] params) { StringBuffer response = new StringBuffer(); HttpClient client = new HttpClient(); PostMethod postMethod = new PostMethod(url); //表单域的值// NameValuePair[] data = {new NameValuePair("name", "test")}; postMethod.setRequestBody(params); //解决中文乱码问题 postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8"); try { int statusCode = client.executeMethod(postMethod); if (statusCode == HttpStatus.SC_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader( postMethod.getResponseBodyAsStream(), charset)); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); } } catch (HttpException e) { SysLog.sysLogError(e.getMessage()); } catch (UnsupportedEncodingException e) { SysLog.sysLogError(e.getMessage()); } catch (IOException e) { SysLog.sysLogError(e.getMessage()); }finally { postMethod.releaseConnection(); } return response.toString(); }

?get提交示例:

/**     * Url Get请求     * @param url url地址     * @param charset 字符编码     * @return     */    public  String doGet(String url, String charset) {        StringBuffer response = new StringBuffer();        HttpClient client = new HttpClient();        HttpMethod method = null;        try {//            String urlPath = URIUtil.encodePath(url);//            String urlPath = URIUtil.encodePath(url, "GBK");            method = new GetMethod(url);            client.executeMethod(method);            if (method.getStatusCode() == HttpStatus.SC_OK) {                BufferedReader reader = new BufferedReader(new InputStreamReader(                    method.getResponseBodyAsStream(), charset));                String line;                while ((line = reader.readLine()) != null) {                    response.append(line);                }                reader.close();            }        } catch (URIException e) {            SysLog.sysLogError("[HTTP GET请求URL字符串编码异常]:: " + e.getMessage());        } catch (IOException e) {            SysLog.sysLogError("[HTTP GET请求URL读写异常]:: " + e.getMessage());        } finally {            method.releaseConnection();        }        return response.toString();    }

?

热点排行