http协议中post方法发出请求

package com.chinaums.szm.test.base.igoodful;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

import java.io.IOException;
import java.util.*;

public class TestPost {

public String doPost(String url, Map<String,String> map, String charset){
CloseableHttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
try{
httpClient = HttpClients.createDefault();
httpPost =new HttpPost(url);
List<NameValuePair> list = new ArrayList<>();
Iterator iterator = map.entrySet().iterator();
while (iterator.hasNext()){
Map.Entry<String,String> entry =(Map.Entry<String,String>) iterator.next();
list.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
}
if (list.size() > 0){
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset);
httpPost.setEntity(entity);
}
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse != null){
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null){
result = EntityUtils.toString(httpEntity,charset);
}
}
}catch (Exception ex){
ex.printStackTrace();
}
return result;
}
@Test
public void test() throws IOException {
String url = "http://admin.tingwen.me/index.php/api/interfaceXykj/touList";
Map<String,String> map = new HashMap<>();
map.put("page","100");
String result = this.doPost(url,map,"UTF-8");
//将输出更加优美的方式展示出。
ObjectMapper mapper = new ObjectMapper();
Object object = mapper.readValue(result,Object.class);
System.out.println( mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object));
}
}

转载于:https://www.cnblogs.com/igoodful/p/9340686.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值