ClientUtil.java
资源名称:MY_PAPA.rar [点击查看]
上传用户:xie_wn
上传日期:2022-03-04
资源大小:941k
文件大小:3k
源码类别:
网络截获/分析
开发平台:
Java
- package com.util;
- import java.io.IOException;
- import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
- import org.apache.commons.httpclient.Header;
- import org.apache.commons.httpclient.HttpClient;
- import org.apache.commons.httpclient.HttpException;
- import org.apache.commons.httpclient.HttpStatus;
- import org.apache.commons.httpclient.NameValuePair;
- import org.apache.commons.httpclient.methods.GetMethod;
- import org.apache.commons.httpclient.methods.PostMethod;
- import org.apache.commons.httpclient.params.HttpMethodParams;
- public class ClientUtil {
- //HttpClient
- public String get(String url)
- {
- HttpClient httpClient = new HttpClient();
- //创建GET方法的实例
- GetMethod getMethod = new GetMethod(url);
- //使用系统提供的默认的恢复策略
- getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
- new DefaultHttpMethodRetryHandler());
- try {
- //执行getMethod
- int statusCode = httpClient.executeMethod(getMethod);
- if (statusCode != HttpStatus.SC_OK) {
- System.err.println("Method failed: "
- + getMethod.getStatusLine());
- }
- //读取内容
- byte[] responseBody = getMethod.getResponseBody();
- //处理内容
- System.out.println(new String(responseBody));
- return new String(responseBody);
- } catch (HttpException e) {
- //发生致命的异常,可能是协议不对或者返回的内容有问题
- System.out.println("Please check your provided http address!");
- e.printStackTrace();
- } catch (IOException e) {
- //发生网络异常
- e.printStackTrace();
- } finally {
- //释放连接
- getMethod.releaseConnection();
- }
- return null;
- }
- public String post(String url,NameValuePair[] data)
- {
- HttpClient httpClient = new HttpClient();
- PostMethod postMethod = new PostMethod(url);
- // 填入各个表单域的值
- //NameValuePair[] data = { new NameValuePair("id", "youUserName"),
- //new NameValuePair("passwd", "yourPwd") };
- postMethod.setRequestBody(data);
- // 执行postMethod
- int statusCode;
- try {
- statusCode = httpClient.executeMethod(postMethod);
- if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY ||
- statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
- // 从头中取出转向的地址
- Header locationHeader = postMethod.getResponseHeader("location");
- String location = null;
- if (locationHeader != null) {
- location = locationHeader.getValue();
- System.out.println("The page was redirected to:" + location);
- } else {
- System.err.println("Location field value is null.");
- }
- }
- byte[] responseBody = postMethod.getResponseBody();
- // System.out.println(new String(responseBody));
- return new String(responseBody);
- } catch (HttpException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return null;
- }
- }