HTTPClient get post 请求方式

使用httpClient 进行远程访问需要在项目中添加   httpclient-3.0.jar  包。

1.post 方式访问:


/**
* POST发送数据
*
* @param url
* @param timeout
* @param params
* @param values
* @return
*/
public static byte[] postData(String url, String postData) {
//创建httpclient 对象
HttpClient client = new HttpClient();
//设置访问超时时间
client.getHttpConnectionManager().getParams().setConnectionTimeout(TIMEOUT);
client.getParams().setParameter("http.socket.timeout", TIMEOUT);
//设置编码集
client.getParams().setContentCharset(CHARSET);
//创建PostMethod 对象 POST 方式提交 如果需要GET 方式提交则 创建 GETMethod 对象
PostMethod method = new PostMethod();
//设置请求头信息
method.addRequestHeader("Content-Type","plain/text;charset=UTF-8");
try {
//向method对象中设置访问路径(IP:端口)
method.setURI(new URI(url, true, CHARSET));
} catch (URIException ex) {
} catch (NullPointerException ex) {
} catch (Exception ex) {
}
//设置POST访问方式要传递的参数
method.setRequestEntity(new StringRequestEntity(postData));
try {
//执行 远程访问请求 方法 Execute the method.
int statusCode = client.executeMethod(method);
//判断返回结果
if (statusCode != HttpStatus.SC_OK) {
return null;
} else {
byte[] responseBody = null;
//获取请求返回的header对象 得到返回的头信息
Header contentEncodingHeader = method.getResponseHeader("Content-Encoding");
//判断如果返回信息是否被压缩
if (contentEncodingHeader != null
&& contentEncodingHeader.getValue().equalsIgnoreCase("gzip")) {
//获取被压缩后的返回信息并解压
GZIPInputStream is = new GZIPInputStream(
method.getResponseBodyAsStream());
ByteArrayOutputStream os = new ByteArrayOutputStream();
IOUtils.copy(is, os);
responseBody = os.toByteArray();
} else {
//获取返回信息 如果返回信息没有被压缩
responseBody = method.getResponseBody();
}

byte[] data = formatData(responseBody);
//方法返回请求结果
return data;
}
} catch (HttpException ex) {
} catch (IOException ex) {
} finally {
// 释放连接
method.releaseConnection();
}
return null;
}



2.GET请求方式

/**
* Get http content from url
* @param url
* @return
* @throws IOException
*/
public static String getHttpContent(String url) throws IOException {
HttpClient client = new HttpClient();
client.getHttpConnectionManager().getParams()
.setConnectionTimeout(TIMEOUT);
client.getParams().setParameter("http.socket.timeout", TIMEOUT);
//Get方式与POST 方式的区别只在此 POSTMethod 与GetMethod Get 方式请求,将请求参数直接拼接在URL后面即可。
GetMethod method = new GetMethod();
try {
method.setURI(new URI(url, false, "utf-8"));

} catch (URIException ex) {
} catch (NullPointerException ex) {
}

//设置发送请求连接数以及请求发送重试功能是否开启 对应参数为:DefaultHttpMethodRetryHandler(8, false)) 8个连接请求数,重新发送请求功能能开启与否 - 否
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(8, false));
try {

int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
return null;
}
byte[] responseBody = null;
Header contentEncodingHeader = method
.getResponseHeader("Content-Encoding");
if (contentEncodingHeader != null
&& contentEncodingHeader.getValue()
.equalsIgnoreCase("gzip")) {
GZIPInputStream is = new GZIPInputStream(
method.getResponseBodyAsStream());
ByteArrayOutputStream os = new ByteArrayOutputStream();
IOUtils.copy(is, os);
responseBody = os.toByteArray();
is.close();
os.close();
} else {
responseBody = method.getResponseBody();
}

byte[] data = formatData(responseBody);
//设置默认编码
String encoding = CHARSET;
//获取请求返回的头信息
Header contentTypeHeader = method.getResponseHeader("Content-Type");
if (contentTypeHeader != null) {
//截取返回信息中的编码
String contentType = contentTypeHeader.getValue();
// //System.out.println("content-type:" + contentType);
int offset = contentType.indexOf("=");
if (offset != -1)
encoding = contentType.substring(offset + 1);
else {
String body = new String(data, encoding);
offset = body.indexOf("encoding");
if (offset != -1) {
int begin = body.indexOf("\"", offset);
int end = body.indexOf("\"", begin + 1);
encoding = body.substring(begin + 1, end);
}
}
}
//根据返回的编码方式得出返回信息串儿
String res = new String(data, encoding);
if(res == null || res.length() > 1024){
}else{
}
return res;

} catch (HttpException ex) {
} catch (IOException ex) {
} finally {
method.releaseConnection();
}
return null;
}




二:上述两种方式 在请求响应效率有些低,如果想要高效率 简单的请求方式,可以使用java自带的 :HttpURLConnection 创建远程连接请求

/**
     * java自带的Http请求处理
     * @param serverId 请求请求指向的是哪个服务器
     * @param cmd 请求命令(指定那种功能的请求)
     * @param boddy 请求需要的数据参数
     * @return
     */
    
    public static String handleHttp(String serverId,String cmd,String boddy){

        try{
            //获取SessionID  仅仅是个唯一标识,为服务器端做为区分请求用
            int sessionId =(int) (new Date().getTime())/1000;
            //设置请求IP+端口
            StringBuilder url = new StringBuilder(Constants.URL);
            //get 方式      拼接参数到URL中
            url.append("sessionId="+sessionId+"&serverId="+serverId+"&cmd="+cmd+"&body="+boddy);
            System.out.println(url.toString());
            URL dataUrl = new URL(url.toString());
            //创建远程连接进行远程访问
            HttpURLConnection con = (HttpURLConnection) dataUrl.openConnection();
            //设置请求超时时间
            con.setConnectTimeout(30000);
            //设置请求方式 GET
            con.setRequestMethod("GET");
            //设置请求头信息
            con.setRequestProperty("Content-Type", "text/html");
            con.setRequestProperty("Connection", "Keep-Alive");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            //获取请求返回信息 流  
            InputStream is = con.getInputStream();
            //处理返回信息流
            BufferedReader buff = new BufferedReader(new InputStreamReader(is,"UTF-8"));
            StringBuilder buffer = new StringBuilder();
            //从请求返回的数据流中读取返回信息 存储到 变量中
            String line = "";
            while ((line = buff.readLine()) != null) {
                buffer.append(line);
            }
            
            String data = buffer.toString();

            buff.close();
            is.close();
            //返回响应信息
            return data;
        }catch(Exception exp){
            //LoggerUtils.temp.error("handlehttperror|"+url, exp);
            return null;
        }
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值