HttpClient (POST GET PUT)请求

package com.curender.web.server.http;

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.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.curender.dal.util.ConstantsDal;

/**
* HttpClient GET POST PUT 请求
* @author huang
* @date 2013-4-10
*/
public class HttpRequest
{

protected static Log log = LogFactory.getLog(HttpRequest.class);
private static HttpRequest httpRequst=null;
private HttpRequest(){}
public static HttpRequest getInstance(){
if(httpRequst==null){
synchronized(HttpRequest.class){
if(httpRequst == null){
httpRequst=new HttpRequest();
}
}
}
return httpRequst;
}

/**
* HttpClient GET请求
* @author huang
* @date 2013-4-9
* @param uri
* @return resStr 请求返回的JSON数据
*/
public String doGet(String uri){
String resStr = null;
HttpClient htpClient = new HttpClient();
GetMethod getMethod = new GetMethod(ConstantsDal.SERVER_URL+uri);
getMethod.getParams().setParameter( HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
try{
int statusCode = htpClient.executeMethod( getMethod );
// log.info(statusCode);
if(statusCode != HttpStatus.SC_OK){
log.error("Method failed: "+getMethod.getStatusLine());
return resStr;
}
byte[] responseBody = getMethod.getResponseBody();
resStr = new String(responseBody,HttpConstants.ENCODED);
} catch (HttpException e) {
log.error("Please check your provided http address!"); //发生致命的异常,可能是协议不对或者返回的内容有问题
} catch (IOException e) {
log.error( "Network anomaly" ); //发生网络异常
}finally{
getMethod.releaseConnection(); //释放连接
}
return resStr;
}

/**
* HttpClient POST请求
* @author huang
* @date 2013-4-9
* @param s_user
* @return resStr 请求返回的JSON数据
*/
@SuppressWarnings( "deprecation" )
public String doPost(String uri,String jsonObj){
String resStr = null;
HttpClient htpClient = new HttpClient();
PostMethod postMethod = new PostMethod(ConstantsDal.SERVER_URL+uri);
postMethod.addRequestHeader( "Content-Type","application/json" );
postMethod.getParams().setParameter( HttpMethodParams.HTTP_CONTENT_CHARSET, HttpConstants.ENCODED );
postMethod.setRequestBody( jsonObj );
try{
int statusCode = htpClient.executeMethod( postMethod );
// log.info(statusCode);
if(statusCode != HttpStatus.SC_OK){
//post和put不能自动处理转发 301:永久重定向,告诉客户端以后应从新地址访问 302:Moved Temporarily
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();
log.info("The page was redirected to :"+location);
}else{
log.info("Location field value is null");
}
}else{
log.error("Method failed: "+postMethod.getStatusLine());
}
return resStr;
}
byte[] responseBody = postMethod.getResponseBody();
resStr = new String(responseBody,HttpConstants.ENCODED);
}catch(Exception e){
e.printStackTrace();
}finally{
postMethod.releaseConnection();
}
return resStr;
}

/**
* HttpClient PUT请求
* @author huang
* @date 2013-4-10
* @return
*/
@SuppressWarnings( "deprecation" )
public String doPut(String uri,String jsonObj){
String resStr = null;
HttpClient htpClient = new HttpClient();
PutMethod putMethod = new PutMethod(ConstantsDal.SERVER_URL+uri);
putMethod.addRequestHeader( "Content-Type","application/json" );
putMethod.getParams().setParameter( HttpMethodParams.HTTP_CONTENT_CHARSET, HttpConstants.ENCODED );
putMethod.setRequestBody( jsonObj );
try{
int statusCode = htpClient.executeMethod( putMethod );
// log.info(statusCode);
if(statusCode != HttpStatus.SC_OK){
log.error("Method failed: "+putMethod.getStatusLine());
return null;
}
byte[] responseBody = putMethod.getResponseBody();
resStr = new String(responseBody,HttpConstants.ENCODED);
}catch(Exception e){
e.printStackTrace();
}finally{
putMethod.releaseConnection();
}
return resStr;
}
}

HttpClient (POST GET PUT)请求的更多相关文章

  1. HttpClient方式模拟http请求设置头

    关于HttpClient方式模拟http请求,请求头以及其他参数的设置. 本文就暂时不给栗子了,当作简版参考手册吧. 发送请求是设置请求头:header HttpClient httpClient = ...

  2. HttpClient发送get post请求和数据解析

    最近在跟app对接的时候有个业务是微信登录,在这里记录的不是如何一步步操作第三方的,因为是跟app对接,所以一部分代码不是由我写,我只负责处理数据,但是整个微信第三方的流程大致都差不多,app端说要传 ...

  3. HttpWebRequest 改为 HttpClient 踩坑记-请求头设置

    HttpWebRequest 改为 HttpClient 踩坑记-请求头设置 Intro 这两天改了一个项目,原来的项目是.net framework 项目,里面处理 HTTP 请求使用的是 WebR ...

  4. 使用HttpClient发送Get/Post请求 你get了吗?

    HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议 ...

  5. org.apache.httpcomponents httpclient 发起HTTP JSON请求

    1. pom.xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactI ...

  6. httpclient的几种请求URL的方式

    一.httpclient项目有两种使用方式.一种是commons项目,这一个就只更新到3.1版本了.现在挪到了HttpComponents子项目下了,这里重点讲解HttpComponents下面的ht ...

  7. HttpClient发起Http/Https请求工具类

    <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcl ...

  8. HttpClient方式模拟http请求

    方式一:HttpClient import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.http.*; im ...

  9. Android HttpClient GET或者POST请求基本使用方法(转)

    在Android开发中我们经常会用到网络连接功能与服务器进行数据的交互,为此Android的SDK提供了Apache的HttpClient来方便我们使用各种Http服务.这里只介绍如何使用HttpCl ...

随机推荐

  1. iOS中富文本NSMutableAttributedString的用法

    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc]initWithString:@"我是富文 ...

  2. gpu对任意长度的矢量求和

    blockDim.x*gridDim.x 跳过一个grid int <<<参数1,参数2>>>(int *a,int * b,int * c); 如果是一维的,参数 ...

  3. ABP 索引

    官方网站 Github ABP集合贴 @ kebinet https://www.codeproject.com/articles/1115763/using-asp-net-core-entity- ...

  4. supervisor监管进程max file descriptor配置不生效的问题

    配置了 sudo vim /etc/security/limits.conf * soft nofile * hard nofile   单独起进程没问题, 放到supervisor下监管启动,则报错 ...

  5. JS 小数的常用处理方法

    1.丢弃小数部分,保留整数部分 parseInt(5/2) 2.向上取整,有小数就整数部分加1 Math.ceil(5/2) 3,四舍五入. Math.round(5/2) 4,向下取整 Math.f ...

  6. chose.jquery 多选

    <select id="language" data-placeholder="选择类别..." class="chosen-select&qu ...

  7. mybatis-generator运行命令

    java -jar mybatis-generator-core-x.x.x.jar -configfile generatorConfig.xml -overwrite

  8. Nginx笔记

    基础篇 关于Nginx Nginx是一款轻量级的Web 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器.最早由俄罗斯的程序设计师Igor Sysoev所开发,并在一个BSD-like ...

  9. UITextField set placeholderColor and UITextField set clearButton Image

    self.usernameTextField.tintColor = [UIColor whiteColor]; [self.usernameTextField setValue:UIColorFro ...

  10. 以冒泡排序为例--malloc/free 重定向stdin stdout

    esort.c 代码如下,可关注下mallloc/free,freopen重定向的用法,排序为每轮将最小的数放在最前面: #include<stdio.h> #include<mal ...