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. unique函数的作用

    unique() 去重函数 unique()函数是一个去重函数,STL中unique的函数 unique的功能是去除相邻的重复元素(只保留一个),还有一个容易忽视的特性是它并不真正把重复的元素删除.他 ...

  2. mvc 4 razor语法讲解和使用

    1.这里的  @{Layout="文件路径";}  代码块指定了整个项目默认所使用的布局文件(如图:) @RenderBody()对于所有的页面默认的情况下都会使用这个布局(Web ...

  3. MapReduce简介

    MapReduce简介 参考自[http://www.cnblogs.com/swanspouse/p/5130136.html] MapReduce定义: MapReduce是一种可用于数据处理的编 ...

  4. [翻译] WCF运行时架构

    原文地址 http://www.cnblogs.com/idior/articles/971252.html 介绍 WCF具有非常易用的编程模型,服务开发者在掌握ABC的概念后可以很容易的使用WCF去 ...

  5. 一个服务器上面配置多个IP ,实现指定IP的域名请求

    //配置多个IP命名using System.Net; //********************************************************************** ...

  6. js call()和apply()

    一.call()和apply(),实例如下: function add(a,b) {     alert(a+b); } function sub(a,b) {     alert(a-b); } a ...

  7. Windows下使用scapy+python2.7实现对pcap文件的读写操作

    scapy在linux环境中对pcap文件进行操作非常方便,但在windows下,特别是在python2.7环境下却会碰到各种各样的依赖包无法使用的问题,最明显的可能就属dnet和pcap的pytho ...

  8. Android学习笔记(一)

    活动(Actiity)是一种可以包含用户界面的组件,主要用于和用户进行交互.一个应用中可以包含零个或多个活动. 所有的自己写Activity都继承于Activity类.项目中的任何活动都应该改重写Ac ...

  9. onmouseover和onmouseout的那些事

    这篇文章来自一个偶然...以前刚开始学习javascript事件的时候就被一个东西搞得晕头撞向的.就是一对名字很相近的事件.一组是onmouseover()和onmouseout().另一组就是onm ...

  10. Django views 中 View decorators

    decorators(装饰器) 1. require_http_methods 在django.views.decorators.http中,可以用来限制请求的权限. require_http_met ...