HttpClient模拟post提交

httpClient模拟post提交jar包3.1版本

public void test() throws Exception{
    String url = "http://192.168.*.*:8080/action";
    //Apache开源组件HttpClient
    HttpClient hc = new HttpClient();
    hc.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");
    PostMethod postMethod=new PostMethod(url);
    //构造方法需要的参数 实体类字段信息
    NameValuePair[] paramValue = new NameValuePair[1];
    paramValue[0] = new NameValuePair("sysType","zhifu");
    postMethod.addParameters(paramValue);
    //设置请求最大延时
    hc.setTimeout(1000*60);
    //返回结果  200为通过
    int result=0;
    try {
      result = hc.executeMethod(postMethod);
      System.out.println("访问考勤系统结果,如果为200,即访问成功!:==>"+result);
      //打印访问的网站源码
      //System.out.println(postMethod.getResponseBodyAsStream());
    } catch (Exception e) {
e.printStackTrace();
    }
//用于判断返回结果集的行
boolean kResult = false;
//临时装结果集用
String temp= "";
//如果成功 200
if (result == HttpStatus.SC_OK) {
StringBuffer contentBuffer = new StringBuffer();
InputStream in = postMethod.getResponseBodyAsStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, postMethod.getResponseCharSet()));
String inputLine = null;
while ((inputLine = reader.readLine()) != null) {
contentBuffer.append(inputLine);
if(kResult){
temp = inputLine;
kResult = false;
}
//判断下一条记录是返回的结果集   这里是根据读取流进行判断的
if(inputLine .endsWith("<body >")){
kResult = true;
}
//换行
contentBuffer.append("/n");
}
in.close();
} else if (result == HttpStatus.SC_MOVED_PERMANENTLY || result == HttpStatus.SC_MOVED_TEMPORARILY) {
// 从头中取出转向的地址   如果访问失败,有其他跳转地址的时候使用
Header locationHeader = postMethod.getResponseHeader("location");
String location = null;
if (locationHeader != null) {
location = locationHeader.getValue();
System.out.println("备用跳转地址:" + location);
} else {
System.err.println("没有备用跳转地址...");
}
}
//结束访问
postMethod.releaseConnection();
}}

猜你喜欢

转载自ye147923.iteye.com/blog/2112307