HttpClient以json形式的参数调用http接口并对返回的json数据进行处理(可以带文件)...

1、参数的url就是被调用的地址,map是你要传的参数。参数转成json我使用的是gson方式转换的。

    主要使用的jar包有httpclient-4.5.3.jar、httpcore-4.4.6.jar、commons-codec-1.9.jar、gson-2.2.4.jar和commons-logging-1.2.jar。

  如果发送的post请求想传送文件,需添加httpmime-4.5.3.jar包,并设置如下代码:

    HttpEntity multipartEntityBuilder = MultipartEntityBuilder.create().addBinaryBody("file", new File("D:\\workspace\\programm\\WebContent\\programm\\1991.zip")).build();

    第一个参数表示请求字段名,第二个参数就是文件。

    还想添加参数则

    HttpEntity multipartEntityBuilder = MultipartEntityBuilder.create().addTextBody("name", "张三").addBinaryBody("file", new File("D:\\workspace\\programm\\WebContent\\programm\\1991.zip")).build();

    httpPost.setEntity(multipartEntityBuilder);

import java.io.IOException;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
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.HttpClients;
import org.apache.http.util.EntityUtils;

import com.google.gson.Gson;

public class HttpClientUtil {
    
    private final static String CONTENT_TYPE_TEXT_JSON = "text/json";
    
    public static String postRequest(String url, Map<String, Object> param) throws ClientProtocolException, IOException{
        
        CloseableHttpClient client = HttpClients.createDefault();

        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
        
        Gson gson = new Gson();
        String parameter = gson.toJson(param);

        StringEntity se = new StringEntity(parameter);
        se.setContentType(CONTENT_TYPE_TEXT_JSON);
        httpPost.setEntity(se);

        CloseableHttpResponse response = client.execute(httpPost);
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity, "UTF-8");
        
        return result;
    }

}

 2、返回的结果也可以使用gson转换成对象进行下一步操作。

import com.google.gson.Gson;

public class GsonUtil {

    public static <T> T jsonToObject(String jsonData, Class<T> type) {
        Gson gson = new Gson();
        T result = gson.fromJson(jsonData, type);
        return result;
    }
    
    public static void main(String[] args) {
        String json = "{'id':'1','name':'zhang','address':'Hubei'}";
        jsonToObject(json, Person.class);
        Person person = jsonToObject(json, Person.class);
        System.out.println(person);
    }

}

建立要转成的对象的类。

import java.util.Date;

public class Person {
    
    private int id;
    
    private String name;
    
    private int age;
    
    private String address;public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Person [id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + "]";
    }

}

 3、发送以键值对形式的参数的post请求

package com.avatarmind.httpclient;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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;

public class HttpClient3 {
    
    public static void main(String[] args) throws Exception {
        CloseableHttpClient client = HttpClients.createDefault();

        String url = "http://yuntuapi.amap.com/datamanage/table/create";

        HttpPost httpPost = new HttpPost(url);

        // 参数形式为key=value&key=value
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("key", "060212638b94290e3dd0648c15753b64"));
        formparams.add(new BasicNameValuePair("name", "火狐"));
                
        // 加utf-8进行编码
        UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
        httpPost.setEntity(uefEntity);

        CloseableHttpResponse response = client.execute(httpPost);
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity, "UTF-8");
        System.out.println(result);
    }

}
    

 

转载于:https://www.cnblogs.com/mengxuanyou/p/6835581.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值