java HttpClient操作工具类
maven:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils; /**
* @author 马弦
* @date 2017年10月23日 下午2:49
* HttpClient工具类
*/
public class HttpUtil { //private static Logger logger = Logger.getLogger(HttpUtil.class); /**
* get请求
* @return
*/
public static String doGet(String url) {
try {
HttpClient client = new DefaultHttpClient();
//发送get请求
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request); /**请求发送成功,并得到响应**/
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
/**读取服务器返回过来的json字符串数据**/
String strResult = EntityUtils.toString(response.getEntity()); return strResult;
}
}
catch (IOException e) {
e.printStackTrace();
} return null;
} /**
* post请求(用于key-value格式的参数)
* @param url
* @param params
* @return
*/
public static String doPost(String url, Map params){ BufferedReader in = null;
try {
// 定义HttpClient
HttpClient client = new DefaultHttpClient();
// 实例化HTTP方法
HttpPost request = new HttpPost();
request.setURI(new URI(url)); //设置参数
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {
String name = (String) iter.next();
String value = String.valueOf(params.get(name));
nvps.add(new BasicNameValuePair(name, value)); //System.out.println(name +"-"+value);
}
request.setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8)); HttpResponse response = client.execute(request);
int code = response.getStatusLine().getStatusCode();
if(code == 200){ //请求成功
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent(),"utf-8"));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
} in.close(); return sb.toString();
}
else{ //
System.out.println("状态码:" + code);
return null;
}
}
catch(Exception e){
e.printStackTrace(); return null;
}
} /**
* post请求(用于请求json格式的参数)
* @param url
* @param params
* @return
*/
public static String doPost(String url, String params) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);// 创建httpPost
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "application/json");
String charSet = "UTF-8";
StringEntity entity = new StringEntity(params, charSet);
httpPost.setEntity(entity);
CloseableHttpResponse response = null; try { response = httpclient.execute(httpPost);
StatusLine status = response.getStatusLine();
int state = status.getStatusCode();
if (state == HttpStatus.SC_OK) {
HttpEntity responseEntity = response.getEntity();
String jsonString = EntityUtils.toString(responseEntity);
return jsonString;
}
else{
//logger.error("请求返回:"+state+"("+url+")");
}
}
finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
} }
java HttpClient操作工具类的更多相关文章
- docker 部署vsftpd服务、验证及java ftp操作工具类
docker部署vsftpd服务 新建ftp文件存储目录/home/ftp cd /home mkdir ftp 创建一个组,用于存放ftp用户 groupadd ftpgroups 创建ftp用户, ...
- JAVA文件操作工具类(读、增、删除、复制)
使用JAVA的JFinal框架 1.上传文件模型类UploadFile /** * Copyright (c) 2011-2017, James Zhan 詹波 (jfinal@126.com). * ...
- Java日期操作工具类
/** * 格式化日期显示格式 * * @param sdate * 原始日期格式 s - 表示 "yyyy-mm-dd" 形式的日期的 String 对象 * @param fo ...
- Java字符串操作工具类
import java.io.ByteArrayOutputStream; import java.io.UnsupportedEncodingException; import java.lang. ...
- Java文件操作工具类(复制、删除、重命名、创建路径)
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import ...
- java时间操作工具类
import java.sql.Timestamp;import java.text.DateFormat;import java.text.ParseException;import java.te ...
- Java文件操作工具类
import com.foriseland.fjf.lang.DateUtil;import org.apache.commons.io.FileUtils;import org.slf4j.Logg ...
- JAVA 数据库操作工具类----sqllite
package com.asc.db; import android.content.ContentValues; import android.content.Context; import and ...
- java/javascript 时间操作工具类
一.java 时间操作工具类 import org.springframework.util.StringUtils; import java.text.ParseException; import ...
随机推荐
- python开源项目聚合推荐【1】
******************************************************* 01项目名:unimatrix 功能介绍:Python模拟“黑客帝国”影片中的终端动画脚 ...
- MQTT研究之EMQ:【eclipse的paho之java客户端使用注意事项】
这里,简单记录一下自己在最近项目中遇到的paho的心得,这里也涵盖EMQX的问题. 1. cleanSession 这个标识,是确保client和server之间是否持久化状态的一个标志,不管是cli ...
- LeetCode 559. Maximum Depth of N-ary Tree(N-Tree的深度)
Given a n-ary tree, find its maximum depth. The maximum depth is the number of nodes along the longe ...
- JS调用onBackPressed
需求: 安卓页面webview加载H5页面,H5页面能能返回到安卓页面 import android.os.Bundle; import android.support.v7.app.AppCompa ...
- Linux CentOS7 下无图形界面安装Oracle11G R2版本
01,系统 Centos7 数据库版本 Oracle_11gR2 ,以及硬件要求 内存不能小于 1G,可用硬盘不小于8G Swap分区空间不小于2G grep MemTotal /proc/memin ...
- 【tensorflow-v2.0】如何将模型转换成tflite模型
前言 TensorFlow Lite 提供了转换 TensorFlow 模型,并在移动端(mobile).嵌入式(embeded)和物联网(IoT)设备上运行 TensorFlow 模型所需的所有工具 ...
- [Go] 环境变量,模块化与基础语法
[环境变量] 安装完 go 之后,设置必要环境变量: export GOPATH=/home/wc/go-lab export GO111MODULE=on export GOPROXY=https: ...
- Idea开发环境中,开发springboot类型的项目,如果只引入parent节点,不添加依赖节点,maven是不会加载springboot的任何依赖的
在SpringBoot类型的项目中,我本来是要使用pringBoot,创建一个Console项目,我原本在pom.xml中添加paren节点了,天真的认为不需要再添加其他任何依赖了,可是接下来的1个小 ...
- CTS/APIO2019 游记
已经记不得是第几天了就按顺序编号好了. 一 久违的到了北京,上次来北京还是在去年CTSC和APIO的时候.回想起来,这一年发生了很多事情啊. 下午是THUPC的试机赛,我和假雪菜.嘿嘿嘿两个神仙队友过 ...
- 【LeetCode】 #7:反转整数 C语言
目录 题目 思路 初步想法 进一步想法 总结 最近打算练习写代码的能力,所以从简单题开始做. 大部分还是用C语言来解决. @(解法) 题目 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数 ...