java 封装httpclient 的get 和post 请求
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 请求的更多相关文章
- Java实现HttpClient发送GET、POST请求(https、http)
1.引入相关依赖包 jar包下载:httpcore4.5.5.jar fastjson-1.2.47.jar maven: <dependency> <groupId>o ...
- [java,2018-01-16] HttpClient发送、接收 json 请求
最近需要用到许多在后台发送http请求的功能,可能需要发送json和xml类型的数据. 就抽取出来写了一个帮助类: 首先判断发送的数据类型是json还是xml: import org.dom4j.Do ...
- java使用HttpClient 发送get、pot请求
package eidolon.messageback.PostUtil; import java.io.BufferedReader; import java.io.IOException; imp ...
- Java 通过HttpClient Post方式提交json请求
package com.sinosoft.ap.harmfullibrary.util; /** * 发送post请求 */import net.sf.json.JSONObject; import ...
- java使用httpclient封装post请求和get的请求
在我们程序员生涯中,经常要复用代码,所以我们应该养成时常整理代码的好习惯,以下是我之前封装的httpclient的post和get请求所用的代码: package com.marco.common; ...
- 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 ...
- Java学习心得之 HttpClient的GET和POST请求
作者:枫雪庭 出处:http://www.cnblogs.com/FengXueTing-px/ 欢迎转载 Java学习心得之 HttpClient的GET和POST请求 1. 前言2. GET请求3 ...
- JAVA使用apache http组件发送POST请求
在上一篇文章中,使用了JDK中原始的HttpURLConnection向指定URL发送POST请求 可以看到编码量有些大,并且使用了输入输出流 传递的参数还是用“name=XXX”这种硬编的字符串进行 ...
- HTTPClient模拟Get和Post请求
一.模拟Get请求(无参) 首先导入HttpClient依赖 <dependency> <groupId>org.apache.httpcomponents</group ...
随机推荐
- hdu4737 A Bit Fun
link:http://acm.hdu.edu.cn/showproblem.php?pid=4737 暴力可以过啊.O(N^2)的复杂度. #include <cstdio> ]; in ...
- 2016.1.4~2016.1.7真题回顾!-- HTML5学堂
2016.1.4~2016.1.7真题回顾!-- HTML5学堂 2015悄然而逝,崭新的2016随即而行!生活需要新鲜感,学习JavaScript的过程需要有成就感!成就感又是来自于每一天的不断练习 ...
- iOS9适配中的各种问题
1.http在ios9上不能在使用.需要进行配置. the resource could not be loaded because the app transport security policy ...
- js封装的方法
1.JS封装就是尽量把使用的方式简单化,内部逻辑和使用解耦.通俗的说就是使用的时候只需要知道参数和返回值,其他条件尽量不要使用人员进行设置. 2.JS封装的方法有函数方式.对象的方式.闭包的方式. 举 ...
- GDB中文手册
用GDB调试程序GDB概述 2使用GDB 5GDB中运行UNIX的shell程序 8在GDB中运行程序 8调试已运行的程序 两种方法: 9暂停 / 恢复程序运行 9一.设置断点(BreakPoint) ...
- Mac下Nginx环境配置
环境信息: Mac OS X 10.11.1 Homebrew 0.9.5 正文 一.安装 Nginx 终端执行: brew search nginx brew install nginx 当前版本 ...
- Vmvare下Ubuntu安装Python3.4
Ubuntu14.4下默认安装的Python版本是2.7.随着Python3.4的使用,现在大部分Python开发者都喜欢使用Py3.4.那么Ubuntu下应该怎么安装Python3.4呢? (1). ...
- [转载]QQ空间技术架构之深刻揭密
1. 拥有5.5亿的活跃用户 2. 过万台的设备 3. 数千万级别的同时在线 4. 数十亿级别的全站PV 5. P级的UGC存储量 6. 每天千亿级别的服务请求 图1--QQ空间海量服务数据规模 接下 ...
- Java学习总结(二)----Java语言基础
1. Java语言基础 2.1 关键字 定义:被java语言赋予特殊含义的单词 特点:关键字中的字母都为小写 用于定义数据类型的关键字 class,interface,byte,short,i ...
- 黄聪:说说JSON和JSONP,也许你会豁然开朗(转)
前言 由于Sencha Touch 2这种开发模式的特性,基本决定了它原生的数据交互行为几乎只能通过AJAX来实现. 当然了,通过调用强大的PhoneGap插件然后打包,你可以实现100%的Socke ...