注:以下用的是commons-httpclient-3.1.jar,往后面的版本写法不一样。
post提交示例:
/**
* 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();
}
注:如果url中有中文参数需要转码,不然会抛异常。
URLEncoder.encode("软件园", "UTF-8")