zoukankan      html  css  js  c++  java
  • 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));
    }
    }
  • 相关阅读:
    Transfer-Encoding: chunked
    使用Kubeadm搭建Kubernetes集群
    连载二:Oracle迁移文章大全
    今晚直播:WLS/WAS故障基本分析介绍
    判断用户是否登录
    row_number() over (partition by a.sql_id order by a.id desc ) r
    Django admin添加用户
    从数据仓库到百万标签库,精细化数据管理,这么做就够了
    用 C 语言开发一门编程语言 — 更好的语言
    ubuntu下 全然卸载火狐浏览器
  • 原文地址:https://www.cnblogs.com/igoodful/p/9340686.html
Copyright © 2011-2022 走看看