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 ...
随机推荐
- Java学习-058-Jsoup爬虫获取中国所有的三级行政区划数据(三),处理二级编码缺失
通过查看数据可知,直辖市或者某些三级行政区域没有对应的二级区域,为方便后续的地址使用,可自定义缺失的二级地址. 如下示例自定义的二级行政区域的名称为一级区域的名称,对应的源码如下所示: 将此段源码添加 ...
- 安装 create-react-app@latest 失败,错误代码:243
在创建react项目,执行以下命令的时候 npx create-react-app my-app 报错如下: 解决方案: 全局安装即可 npm install -g create-react-app
- MySQL 使用 ON UPDATE CURRENT_TIMESTAMP 自动更新 timestamp (转)
原文地址: https://blog.csdn.net/heatdeath/article/details/79833492 `create_time` timestamp not null defa ...
- Anaconda + PyCharm + Pytorch
Anaconda 1. 下载Anaconda https://www.anaconda.com/download/ 2. 安装 3. 添加环境变量 Path - C:\Users\Godzilla ...
- (十)redis源码解读
一.redis工作机制 redis是 单线程,所有命令(set,get等)都会加入到队列中,然后一个个执行. 二.为什么redis速度快? 1.基于内存 2.redis协议resp 简单.可读.效率高 ...
- Android 问题解决 HorizontalScrollView显示不全(转)
原链接:https://www.jianshu.com/p/003adbcaff9d Android 问题解决 HorizontalScrollView显示不全 <HorizontalScrol ...
- elasticsearch-head
elasticsearch-head 是用于监控 Elasticsearch 状态的客户端插件,包括数据可视化.执行增删改查操作等 安装前先安装nodejs 1.下载 地址 2.安装 npm ins ...
- Spring Boot启动时出现WARN:No MyBatis mapper was found in
今天发现spring-boot继承mybatis启动时老是出现WARN: org.mybatis.spring.mapper.ClassPathMapperScanner - No MyBatis m ...
- 打开nginx配置的站点报错500
打开站点报错500的原因 有很多,这里只说明一点:nginx 的fastcgi.conf配置引起的问题 环境说明 1 站点目录结构 wwwroot website public application ...
- socket-02
# -- coding: utf-8 -- _author__ = "HuaQiang Yan" import socket def handle_request(client): ...