0
点赞
收藏
分享

微信扫一扫

java post接口测试代码

package com.example.day02;



import java.io.IOException;

import java.util.ArrayList;

import java.util.List;



import org.apache.http.Consts;

import org.apache.http.NameValuePair;

import org.apache.http.client.ClientProtocolException;

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 PostDemo {

public void doPost() throws ClientProtocolException, IOException{

//1.新建一个客户端对象

CloseableHttpClient client=HttpClients.createDefault();

//实例化一个post对象

HttpPost post=new HttpPost("http://172.31.6.94:8080/130iftest/Calc");

// 使用NameValuePair将发送的参数打包

List<NameValuePair> list=new ArrayList<NameValuePair>();

//打包

list.add(new BasicNameValuePair("a", "2"));

list.add(new BasicNameValuePair("b", "3"));

//使用URLEncodedFormEntity工具类实现一个entity对象,并使用NameValuePair中的数据进行初始化

UrlEncodedFormEntity formEntity=new UrlEncodedFormEntity(list,Consts.UTF_8);

//将实例化的
entity对象放到post对象的请求体中

post.setEntity(formEntity);

//建立一个响应对象,
接受客户端执行post后的响应结果

CloseableHttpResponse response=client.execute(post);

//从实体中提取结果数据

String result=EntityUtils.toString(response.getEntity());

System.out.println(result);


}

public static void main(String[] args) throws ClientProtocolException, IOException {

PostDemo postDemo=new PostDemo();

postDemo.doPost();



}








}

举报

相关推荐

0 条评论