HttpClient 使用对servlet推送数据


本人使用的是3.0.1版本 ,现在已经是4.0版本以后了,版本区别很大方法就不同,4.0是使用的接口。。
import org.apache.commons.httpclient.HttpClient
import org.apache.commons.httpclient.methods.PostMethod
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpMethodParams;



public static String setUevent(url){
HttpClient       httpClient   = new HttpClient();
PostMethod method  = new PostMethod(url)
method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");//防止中文乱码

这里有两种传参方法
1、
method.addParameter("user", 'user');//使用string类型不是的记得.toString()
method.addParameter("pass",  'pass');
httpClient.executeMethod(method);
method.releaseConnection();//记得关闭
2、
NameValuePair[] data =[
new NameValuePair("CLIENT_ID", uevent.clientcmy.id.toString()),
new NameValuePair("CONTENT",  uevent.content.toString())
]
method.setRequestBody(data);
try {
httpClient.getParams().setContentCharset("GBK");
// 执行postMethod
int statusCode = httpClient.executeMethod(method);
// HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发
// 301或者302
//    if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
//      || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
//     String responseBody = postMethod.getResponseBodyAsString();
//     log.info(responseBody);
//     if (responseBody != null) {
//      if ("succ".equals(responseBody)) { // 发送成功
//
//       isSended = true;
//      }
//     }
//    }

if (statusCode == 200) {
strResponse = method.getResponseBodyAsString();
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (HttpException e) {
// 发生致命的异常,可能是协议不对或者返回的内容有问题

e.printStackTrace();
} catch (IOException e) {
// 发生网络异常
e.printStackTrace();
} finally {
// 释放连接
method.releaseConnection();
}



}

你可能感兴趣的:(httpclient)