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. android之ViewPager

    在android中ViewPager是非常常用的控件.它在android.support.v4.view.ViewPager下.你们自己可以进http://developer.android.com/ ...

  2. 使用POI设置excel背景色

    HSSFCellStyle setBorder1 = workbook.createCellStyle(); HSSFFont font1 = workbook.createFont(); font1 ...

  3. (转) Graph-powered Machine Learning at Google

        Graph-powered Machine Learning at Google     Thursday, October 06, 2016 Posted by Sujith Ravi, S ...

  4. hbase-architecture

    https://www.mapr.com/blog/in-depth-look-hbase-architecture http://stackoverflow.com/questions/400679 ...

  5. Centreon插件nagvis

    ======================================= http://docs.nagvis.org/1.8/en_US/index.html https://document ...

  6. 用Sublime Text搭建简易IDE编写Verilog代码

    前言 Verilog是一种硬件描述语言(HDL),该语言在Windows上有集成开发环境可以使用,如ModelSim,但ModelSim的编辑器不太好用因此笔者萌生了用Sublime Text3来编写 ...

  7. fiddler web开发调试工具的使用

    fiddler使用场景: (1)开发环境host配置: 通常情况下,配置host需要改变系统文件很不方便,在多个开发环境下切换很低效 fiddler提供了相对高效的host配置方法 (2)前后端接口调 ...

  8. Zookeeper安装指南

    第一步:修改conf目录下面的 zoo_sample.cfg修改为zoo.cfg tickTime=2000 # The number of ticks that the initial # sync ...

  9. Reflector 反编译 .NET文件后修复

    反编译后的工程文件用VS2010打开后,在打开窗体时会出现一系列错误提示: 第一种情况: “设计器无法处理第 152 行的代码: base.AutoScaleMode = AutoScaleMode. ...

  10. OneNote 2013 快捷键

    越来越喜欢onenote这个笔记本软件,找了下提高效率的办法,收藏学习下: 转载自:http://onenoter.com/2013/04/5792 记录笔记和设置笔记格式 键入和编辑笔记 操作 按键 ...