java get请求json参数,httpClient包实现带hreader和参数的get请求内容为json格式的post请求...

直接上代码,项目时maven项目,需要在pom文件中导入代码中需要引用的jar包;

package com.jokin.learn.HttpTools;

import com.alibaba.druid.support.logging.Log;

import com.alibaba.druid.support.logging.LogFactory;

import org.apache.http.*;

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.client.utils.URIBuilder;

import org.apache.http.entity.StringEntity;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.net.URISyntaxException;

import java.nio.charset.Charset;

import java.util.List;

import java.util.Map;

public class HttpUtil {

private Log logger = LogFactory.getLog(this.getClass());

private static final String pattern = "yyyy-MM-dd HH:mm:ss:SSS";

/**

*实现get请求

* @param baseUrl

* @param parameters 传入参数的map;当无参数时,传入的map=null即可

* @param headers 传入header的map, 例如cookies等,当无值时,传入null即可

* @return

*/

public String get1(String baseUrl,Map parameters ,Map headers ){

//创建一个httpclient对象

CloseableHttpClient httpClient = HttpClients.createDefault();

//创建一个返回值对象

CloseableHttpResponse response = null;

String entityString=null;

try {

URIBuilder uriBuilder = new URIBuilder(baseUrl);

if(parameters!=null&&parameters.size()>0){

for (Map.Entry temp : parameters.entrySet() ) {

//循环map里面的每一对键值对,然后获取key和value即时想要的参数的 key和value

uriBuilder.addParameter(temp.getKey(),temp.getValue());

}

}

/*URIBuilder uriBuilder = new URIBuilder("http://www.sogou.com/web");

uriBuilder.addParameter("query", "花千骨");*/

HttpGet get = new HttpGet(uriBuilder.build());//生产一个httpget连接

//添加head, 用setheader 如果已经存在就重置, addheader如果已经存在进行新增同名的header

if(headers!=null&&headers.size()>0){

for (Map.Entry temp : headers.entrySet() ) {

//循环map里面的每一对键值对,然后获取key和value即时想要的参数的 key和value

get.setHeader(temp.getKey(),temp.getValue());

}

}

//执行请求

response = httpClient.execute(get);

//取响应的结果

int statusCode = response.getStatusLine().getStatusCode();

System.out.println(statusCode);

HttpEntity entity = response.getEntity();

entityString = EntityUtils.toString(entity, "utf-8");

System.out.println(entityString);

} catch (URISyntaxException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

if(response !=null){

response.close();

}

if (httpClient!=null){

httpClient.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

return entityString;

}

/**

* 传入的参数为Json格式的的post请求实现方式

* @param baseUrl

* @param parameters

* @return

*/

public String post(String baseUrl,String parameters) {

//CloseableHttpClient 实现了HttpClient, Closeable两个接口

CloseableHttpClient httpClient = HttpClients.createDefault();

HttpPost postmethod = new HttpPost(baseUrl);

//创建一个uri对象

CloseableHttpResponse response = null;

long startTime = 0L;

long endTime = 0L;

int status = 0;

String bodyString = null;

logger.info("parameters:" + parameters);

if (postmethod != null ) {

try {

// 建立一个NameValuePair数组,用于存储欲传送的参数

postmethod.addHeader("Content-type","application/json; charset=utf-8");

postmethod.setHeader("Accept", "application/json");

if(parameters != null && !"".equals(parameters.trim())){

postmethod.setEntity(new StringEntity(parameters, Charset.forName("UTF-8")));

}

startTime = System.currentTimeMillis();

response = httpClient.execute(postmethod);

endTime = System.currentTimeMillis();

int statusCode = response.getStatusLine().getStatusCode();

logger.info("statusCode:" + statusCode);

logger.info("调用API 花费时间(单位:毫秒):" + (endTime - startTime));

if (statusCode != HttpStatus.SC_OK) {

logger.error("Method failed:" + response.getStatusLine());

status = 1;

}

// Read the response body

bodyString = EntityUtils.toString(response.getEntity());

} catch (IOException e) {

// 网络错误

status = 3;

} finally {

logger.info("调用接口状态:" + status);

try {

if(response !=null){

response.close();

}

if (httpClient!=null){

httpClient.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

return bodyString;

}

/**

* get带参调用方式二

* @param url

* @param parametersList

* @return

*/

public String get2(String url ,List parametersList) {

CloseableHttpClient httpClient = HttpClients.createDefault();

CloseableHttpResponse response = null;

InputStream is = null;

String entityString =null;

String baseUrl =url;

//String baseUrl = "http://localhost:8080/MyWebxTest/getCityByProvinceEname.do";

/*//封装请求参数

List params = Lists.newArrayList();

params.add(new BasicNameValuePair("cityEname", "henan"));*/

String str = "";

try {

//转换为键值对

str = EntityUtils.toString(new UrlEncodedFormEntity(parametersList, Consts.UTF_8));

System.out.println(str);

//创建Get请求

HttpGet httpGet = new HttpGet(baseUrl+"?"+str);

//执行Get请求,

response = httpClient.execute(httpGet);

//得到响应体

HttpEntity entity= response.getEntity();

entityString = EntityUtils.toString(entity);

if(entity != null){

is = entity.getContent();

//转换为字节输入流

BufferedReader br = new BufferedReader(new InputStreamReader(is, Consts.UTF_8));

String body = null;

while((body=br.readLine()) != null){

System.out.println(body);

}

}

} catch (ParseException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally{

//关闭输入流,释放资源

if(is != null){

try {

is.close();

} catch (IOException e) {

e.printStackTrace();

}

}

//消耗实体内容

if(response != null){

try {

response.close();

} catch (IOException e) {

e.printStackTrace();

}

}

//关闭相应 丢弃http连接

if(httpClient != null){

try {

httpClient.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

return entityString;

}

}

转载至链接:https://my.oschina.net/u/3160044/blog/1935201

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值