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(); }
?