import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair; public class HttpUtil { /**
* 以Post方法访问
* @param url 请求地址
* @param paramsMap 携带的参数
* @return String 返回结果
* @throws Exception
*/
@SuppressWarnings("deprecation")
public static String postMethod(String url, Map<String, Object> paramsMap){
String result = "SUCCESS";
try {
byte[] dataByte = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
UrlEncodedFormEntity encodedFormEntity = new UrlEncodedFormEntity(setHttpParams(paramsMap), "UTF-8");
httpPost.setEntity(encodedFormEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
if (!checkNetwork(httpResponse)) {
result = "LINK FAILURE!";
return result;
}
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
byte[] responseBytes = getData(httpEntity);
dataByte = responseBytes;
httpPost.abort();
}
result = bytesToString(dataByte);
} catch (Exception e) {
result = "FAILURE";
e.printStackTrace();
}
return result;
} /**
* 以Get方法访问
* @param url 请求地址
*/
public static String GETMethod(String url,Map<String, Object> paramsMap){
String result = "SUCCESS";
try{
byte[] dataByte = null;
HttpClient httpClient = new DefaultHttpClient();
//为GET请求链接构造参数
url = formatGetParameter(url,paramsMap);
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
if (!checkNetwork(httpResponse)) {
result = "LINK FAILURE!";
return result;
}
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
byte[] responseBytes = getData(httpEntity);
dataByte = responseBytes;
httpGet.abort();
}
result = bytesToString(dataByte);
}catch(Exception e){
result = "LINK FAILURE!";
e.printStackTrace();
}
return result;
} /**
* 以Put方法访问
* @param url 请求地址
*/
public static String PUTMethod(String url,Map<String, Object> paramsMap){
String result = "SUCCESS";
try {
byte[] dataByte = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPut httpPut = new HttpPut(url);
UrlEncodedFormEntity encodedFormEntity = new UrlEncodedFormEntity(setHttpParams(paramsMap), "UTF-8");
httpPut.setEntity(encodedFormEntity);
HttpResponse httpResponse = httpClient.execute(httpPut);
if (!checkNetwork(httpResponse)) {
result = "LINK FAILURE!";
return result;
}
// 获取返回的数据
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
byte[] responseBytes = getData(httpEntity);
dataByte = responseBytes;
httpPut.abort();
}
result = bytesToString(dataByte);
} catch (Exception e) {
result = "LINK FAILURE!";
e.printStackTrace();
}
return result;
} /**
* 构造GET请求地址的参数拼接
* @param url
* @param paramsMap
* @return String
*/
private static String formatGetParameter(String url, Map<String, Object> paramsMap) {
if (paramsMap != null && !paramsMap.isEmpty()) {
if (url != null && url.length() > 0) {
if (!url.endsWith("?")) {
url = url + "?";
}
Set<Entry<String, Object>> entrySet = paramsMap.entrySet();
Iterator<Entry<String, Object>> iterator = entrySet.iterator();
while (iterator.hasNext()) {
Entry<String, Object> entry = iterator.next();
if (entry != null) {
String key = entry.getKey();
String value = (String) entry.getValue();
url = url + key + "=" + value;
if (iterator.hasNext()) {
url = url + "&";
}
}
}
}
}
return url;
} /**
* 获取数据
* @param httpEntity
*/
private static byte[] getData(HttpEntity httpEntity) throws Exception{
BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(httpEntity);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bufferedHttpEntity.writeTo(byteArrayOutputStream);
byte[] responseBytes = byteArrayOutputStream.toByteArray();
return responseBytes;
} /**
* 设置HttpPost请求参数
* @param paramsMap
* @return BasicHttpParams
*/
private static List<BasicNameValuePair> setHttpParams(Map<String, Object> paramsMap){
List<BasicNameValuePair> nameValuePairList = new ArrayList<BasicNameValuePair>();
if (paramsMap!=null && !paramsMap.isEmpty()) {
Set<Entry<String, Object>> set = paramsMap.entrySet();
Iterator<Entry<String, Object>> iterator = set.iterator();
while(iterator.hasNext()){
Entry<String, Object> entry = iterator.next();
BasicNameValuePair basicNameValuePair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
nameValuePairList.add(basicNameValuePair);
}
}
return nameValuePairList;
} /**
* 将字节数组转换成字符串
* @param bytes
*/
private static String bytesToString(byte[] bytes) throws UnsupportedEncodingException{
if (bytes!=null) {
String returnStr = new String(bytes,"utf-8");
return returnStr;
}
return null;
} /**
* 判断网络连接是否成功
*/
public static boolean checkNetwork(HttpResponse httpResponse){
if (httpResponse.getStatusLine().getStatusCode() == 200) {
return true;
}
return false;
}
}

java 封装httpclient 的get 和post 请求的更多相关文章

  1. Java实现HttpClient发送GET、POST请求(https、http)

    1.引入相关依赖包 jar包下载:httpcore4.5.5.jar    fastjson-1.2.47.jar maven: <dependency> <groupId>o ...

  2. [java,2018-01-16] HttpClient发送、接收 json 请求

    最近需要用到许多在后台发送http请求的功能,可能需要发送json和xml类型的数据. 就抽取出来写了一个帮助类: 首先判断发送的数据类型是json还是xml: import org.dom4j.Do ...

  3. java使用HttpClient 发送get、pot请求

    package eidolon.messageback.PostUtil; import java.io.BufferedReader; import java.io.IOException; imp ...

  4. Java 通过HttpClient Post方式提交json请求

    package com.sinosoft.ap.harmfullibrary.util; /** * 发送post请求 */import net.sf.json.JSONObject; import ...

  5. java使用httpclient封装post请求和get的请求

    在我们程序员生涯中,经常要复用代码,所以我们应该养成时常整理代码的好习惯,以下是我之前封装的httpclient的post和get请求所用的代码: package com.marco.common; ...

  6. JAVA发送HttpClient请求及接收请求结果

    1.写一个HttpRequestUtils工具类,包括post请求和get请求 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 2 ...

  7. Java学习心得之 HttpClient的GET和POST请求

    作者:枫雪庭 出处:http://www.cnblogs.com/FengXueTing-px/ 欢迎转载 Java学习心得之 HttpClient的GET和POST请求 1. 前言2. GET请求3 ...

  8. JAVA使用apache http组件发送POST请求

    在上一篇文章中,使用了JDK中原始的HttpURLConnection向指定URL发送POST请求 可以看到编码量有些大,并且使用了输入输出流 传递的参数还是用“name=XXX”这种硬编的字符串进行 ...

  9. HTTPClient模拟Get和Post请求

    一.模拟Get请求(无参) 首先导入HttpClient依赖 <dependency> <groupId>org.apache.httpcomponents</group ...

随机推荐

  1. 大道至简---软件工程实践者的思想------------java伪代码形式读后感第一章

    import.java.大道至简.*; 1.编程的精义----愚公移山 /* 原始需求的产生:惩山北之塞,出入之迂 项目沟通的基本方式:聚室而谋曰 项目的目标:毕力平险,指通豫南,达于汉阴 技术方案: ...

  2. GDB中文手册

    用GDB调试程序GDB概述 2使用GDB 5GDB中运行UNIX的shell程序 8在GDB中运行程序 8调试已运行的程序 两种方法: 9暂停 / 恢复程序运行 9一.设置断点(BreakPoint) ...

  3. mysql特殊处理

    mysql> create table ef (bc time);Query OK, 0 rows affected (0.03 sec) mysql> insert into ef va ...

  4. CSS 知识点

    1:display:block:比较常用于<a><span>这两个标签——因为这两个标签非块元素,如果不用display:block定义一下,因为a标签没有结构,就是没有宽高, ...

  5. 【C】 05 - 声明和定义

    仅从形式上看,C程序就是由各种声明和定义组成的.它们是程序的骨架和外表,不仅定义了数据(变量),还定义了行为(函数).规范中的纯语言部分,声明和定义亦花去了最多的篇幅.完全说清定义的语法比较困难,这里 ...

  6. java 集合的使用 (一)

    1.使用整型列表 List<int> lstInt=new List<int>(); 结果不对,报的错误是:Syntax error, insert "Dimensi ...

  7. CAD的API们

    AutoCAD有4种API,.net,lisp,activex和ObjectARX(C++).它们都是用来给cad写插件什么的,依赖cad运行. 另有一个RealDWG SDK,这是用来读写dwg或d ...

  8. ASP.NET MVC Web API 学习笔记---第一个Web API程序

    http://www.cnblogs.com/qingyuan/archive/2012/10/12/2720824.html GetListAll /api/Contact GetListBySex ...

  9. C#禁止程序重复启动

    采用线程互斥锁Mutex,在winform程序的主入口点中加入如下代码,将程序改为单实例运行. static class Program { /// <summary> /// 应用程序的 ...

  10. activiti自定义流程之整合(六):获取我的申请任务

    流程启动后,流程节点便进入到了任务相关的部分.可以看到我之前的做法是在启动节点就绑定了form表单,启动时就填写相关的数据.实际上在之前我的做法是不对开始节点做任何操作,知道任务节点的时候再填写相关的 ...