HTTPCLIENT POST GET请求模拟

来源:互联网 发布:淘宝店铺如何上货 编辑:程序博客网 时间:2024/05/14 01:29

一、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
原创粉丝点击