HTTPCLIENT POST GET请求模拟

一、POST请求:

private static void post(String url) {
		PostMethod postMethod = null;
		GetMethod getMethod = null;
		String captchaCode = "0251";
		String sessionId = "r0fud17p49zenksx97uzdre7";
		try {
			HttpClient client = new HttpClient();
			postMethod = new PostMethod(url);
			NameValuePair[] arr = new NameValuePair[3];
			NameValuePair username = new NameValuePair("username","ppt");
			arr[0] = username;
			NameValuePair password = new NameValuePair("password","ppt");
			arr[1] = password;
			NameValuePair captcha = new NameValuePair("captcha",captchaCode);
			arr[2] = captcha;
			postMethod.setRequestHeader("Cookie", "JSESSIONID="+sessionId);
			postMethod.setRequestBody(arr);
			int status = client.executeMethod(postMethod);
			if(status == HttpStatus.SC_MOVED_TEMPORARILY) {
				Header[] header = postMethod.getResponseHeaders();
				for(Header hh : header) {
					String headerName = hh.getName();
					if("Location".equals(headerName)) {
						String value = hh.getValue();
						getMethod = new GetMethod(value);
						getMethod.setRequestHeader("Cookie", "JSESSIONID="+sessionId);
						int statu = client.executeMethod(getMethod);
						if(statu == HttpStatus.SC_OK) {
							String str = getMethod.getResponseBodyAsString();
							System.out.println(str);
						}
					}
				}
			}
			if(status == HttpStatus.SC_OK) {
				String content = postMethod.getResponseBodyAsString();
				System.out.println(content);
			} else {
				System.out.println("http status: " + status);
			}
		} catch(Exception e) {
			e.printStackTrace();
		} finally {
			if(postMethod != null) {
				postMethod.releaseConnection();
			}
			if(getMethod != null) {
				getMethod.releaseConnection();
			}
			
		}
	}

二、GET 请求:

private static void get(String url) {
		GetMethod method = null;
		try {
			HttpClient client = new HttpClient();
			method = new GetMethod(url);
			method.setRequestHeader("Cookie", "JSESSIONID=2D94ED969F39054DDB4444CFE24F550F");
			int status = client.executeMethod(method);
			if(status == HttpStatus.SC_OK) {
				String content = method.getResponseBodyAsString();
				System.out.println(content);
			} else {
				System.out.println("http status:" + status);
			}
		} catch(Exception e) {
			e.printStackTrace();
		} finally {
			method.releaseConnection();
		}
	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值