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. shell及脚本3——正则表达式

    一.正则表达式 1.1. 什么是正则表达式 正则表达式是处理字符串的方法,以行为单位,通过一些特殊符号的辅助,让用户可以轻易进行查找.删除.替换某特定字符串的操作. 1.2. 正则表达式与通配符的区别 ...

  2. react-redux原理分析

    写在前面 之前写了一篇分析Redux中Store实现的文章(详见:Redux原理(一):Store实现分析),突然意识到,其实React与Redux并没有什么直接的联系.Redux作为一个通用模块,主 ...

  3. Angular select 绑定复杂类型 设置默认项

    <select ng-model="selectedTask" ng-options="s.name for s in TaskList">< ...

  4. 图说C++对象模型:对象内存布局详解

    0.前言 文章较长,而且内容相对来说比较枯燥,希望对C++对象的内存布局.虚表指针.虚基类指针等有深入了解的朋友可以慢慢看. 本文的结论都在VS2013上得到验证.不同的编译器在内存布局的细节上可能有 ...

  5. MATLAB的三维散点图

    MATLAB中三维散点图函数为scatter3(x,y,z) 三维火柴图为stem3(x,y,z)

  6. django models进行数据库增删查改

    在cmd 上运行 python manage.py shell   引入models的定义 from app.models import  myclass   ##先打这一行    ------这些是 ...

  7. linux 7z 命令编译安装

    7zip是一个开源的压缩软件  7z格式是压缩率最高的格式 服务器备份 数据几个g 要是tar压缩下载的话 时间太长  7zip压缩出来体积很小 首先安装 我这是 centos的 直接可以  yum ...

  8. 移动端阻止body滚动

    一些移动设备有缺省的touchmove行为,比如说经典的iOS overscroll效果,当滚动超出了内容的界限时就引发视图反弹 阻止滚动: css: body{ height:100%; overf ...

  9. 解决SmartGit序列号问题

    SmartGit过了30天试用期之后,就需要用户输入序列号才能继续使用,有一个办法可以跳过输入序列号. 一.windows+R  输入:%APPDATA%\syntevo\SmartGit 二.打开7 ...

  10. easyUI 如何不跳转页面,只是加载替换center部分内容

    以前做的一个故障报修系统,前端框架使用easyUI框架,layout布局,center使用datagrid .点击左边树形菜单时时页面跳转,想要知道如何点击菜单时不进行页面跳转,而是只对center模 ...