restclient发送json_java如何通过client客戶端http实现get/ post请求传递json参数到restful 服务接口...

一、首先在client端,导入maven相关依赖(httpclient以及json相关依赖)

org.apache.httpcomponents

httpclient

4.5.2

net.sf.json-lib

json-lib

2.4

net.sf.ezmorph

ezmorph

1.0.6

commons-collections

commons-collections

3.2.1

commons-beanutils

commons-beanutils

1.8.3

二、程序实例

import java.io.IOException;

import java.net.URI;

import java.util.ArrayList;

import java.util.List;

import java.util.Map;

import org.apache.http.Consts;

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.HttpGet;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.client.utils.URIBuilder;

import org.apache.http.entity.ContentType;

import org.apache.http.entity.StringEntity;

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 net.sf.json.JSONObject;

public class HttpClientUtil {

public static String doGet(String url, Map param) {

// 创建Httpclient对象

CloseableHttpClient httpclient = HttpClients.createDefault();

//设置请求超时时间(各项超时参数具体含义链

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用RestSharp库可以方便地实现GET和POST请求,并发送JSON参数。以下是使用RestSharp进行GET和POST请求的示例代码: 首先,确保你已经在项目中安装了RestSharp库。你可以通过NuGet包管理器或手动下载并添加引用来完成安装。 GET请求示例: ```csharp using RestSharp; using System; namespace RestSharpExample { class Program { static void Main(string[] args) { // 创建RestClient实例并设置请求的URL var client = new RestClient("https://example.com/api/endpoint"); // 创建GET请求 var request = new RestRequest(Method.GET); // 添加请求参数(可选) request.AddParameter("key", "value"); // 执行请求 var response = client.Execute(request); // 检查响应是否成功 if (response.IsSuccessful) { // 读取响应内容 Console.WriteLine(response.Content); } else { Console.WriteLine("请求失败: " + response.StatusCode); } } } } ``` POST请求示例: ```csharp using RestSharp; using System; namespace RestSharpExample { class Program { static void Main(string[] args) { // 创建RestClient实例并设置请求的URL var client = new RestClient("https://example.com/api/endpoint"); // 创建POST请求 var request = new RestRequest(Method.POST); // 添加请求头(可选) request.AddHeader("Content-Type", "application/json"); // 添加JSON参数 request.AddJsonBody(new { key1 = "value1", key2 = "value2" }); // 执行请求 var response = client.Execute(request); // 检查响应是否成功 if (response.IsSuccessful) { // 读取响应内容 Console.WriteLine(response.Content); } else { Console.WriteLine("请求失败: " + response.StatusCode); } } } } ``` 请将`https://example.com/api/endpoint`替换为实际的目标URL,并根据需要修改请求参数和头部信息。以上示例代码可以帮助你发送GET和POST请求,并发送JSON参数
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值