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

<dependencies><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.2</version></dependency><dependency><groupId>net.sf.json-lib</groupId><artifactId>json-lib</artifactId><version>2.4</version></dependency><dependency><groupId>net.sf.ezmorph</groupId><artifactId>ezmorph</artifactId><version>1.0.6</version></dependency><dependency><groupId>commons-collections</groupId><artifactId>commons-collections</artifactId><version>3.2.1</version></dependency><dependency><groupId>commons-beanutils</groupId><artifactId>commons-beanutils</artifactId><version>1.8.3</version></dependency></dependencies>

二、程序实例

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<String, String> param) { // 创建Httpclient对象 CloseableHttpClient httpclient = HttpClients.createDefault(); //设置请求超时时间(各项超时参数具体含义链接)RequestConfig requestConfig = RequestConfig.custom()         .setConnectTimeout(10000).setConnectionRequestTimeout(10000).setSocketTimeout(10000).build();String resultString = ""; CloseableHttpResponse response = null; try { // 创建uri URIBuilder builder = new URIBuilder(url); if (param != null) { for (String key : param.keySet()) { builder.addParameter(key, param.get(key)); } } URI uri = builder.build(); // 创建http GET请求 HttpGet httpGet = new HttpGet(uri); //给这个请求设置请求配置httpGet.setConfig(requestConfig);httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2");// 执行请求 response = httpclient.execute(httpGet); // 判断返回状态是否为200 if (response.getStatusLine().getStatusCode() == 200) { resultString = EntityUtils.toString(response.getEntity(), "UTF-8"); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (response != null) { response.close(); } httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; } public static String doPost(String url, Map<String, String> param) { // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); //设置请求超时时间RequestConfig requestConfig = RequestConfig.custom()         .setConnectTimeout(10000).setConnectionRequestTimeout(10000).setSocketTimeout(10000).build();CloseableHttpResponse response = null; String resultString = ""; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); httpPost.setConfig(requestConfig);// 创建参数列表 if (param != null) { List<NameValuePair> paramList = new ArrayList<>(); for (String key : param.keySet()) { paramList.add(new BasicNameValuePair(key, param.get(key))); } // 模拟表单 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList); httpPost.setEntity(entity); } // 执行http请求 response = httpClient.execute(httpPost); if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){resultString = EntityUtils.toString(response.getEntity(), "utf-8"); }} catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return resultString; } public static String doPostJson(String url, String json) { // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); //设置请求超时时间RequestConfig requestConfig = RequestConfig.custom()         .setConnectTimeout(10000).setConnectionRequestTimeout(10000).setSocketTimeout(10000).build();CloseableHttpResponse response = null; String resultString = ""; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); httpPost.setConfig(requestConfig);// 创建请求内容 ,发送json数据需要设置contentTypeStringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON));httpPost.setEntity(entity); // 执行http请求 response = httpClient.execute(httpPost); if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){resultString = EntityUtils.toString(response.getEntity(), "utf-8"); }} catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return resultString; }
}

补充:各项超时参数具体含义链接

1、发送普通格式数据:

客户端代码:

public static void httpClientTest(){String url="http://localhost/SSMActM/RestTest/restMethod";Map<String,String> map=new HashMap<String,String> ();map.put("name", "bob");map.put("id", "2");String str = HttpClientUtil.doGet(url, map);System.out.println(str);
}

服务端:

@RequestMapping(value = "/restMethod")
@ResponseBody
public String restMethod(HttpServletRequest request){String username = request.getParameter("name");return username;
}

2、发送json格式数据:

客户端代码:

public static void httpClientJsonTest(){String url="http://localhost/SSMActM/RestTest/restMethod";Map<String,String> map=new HashMap<String,String> ();map.put("name", "bob");map.put("id", "2");//post使用json格式String param=JSONObject.fromObject(map).toString();String str = HttpClientUtil.doPostJson(url,param);System.out.println(str);
}

服务端:

@RequestMapping(value = "/restMethod")
public String restMethod(HttpServletRequest request){StringBuffer str = new StringBuffer();  try { BufferedInputStream in = new BufferedInputStream(request.getInputStream()); int i; char c; while ((i=in.read())!=-1) { c=(char)i; str.append(c); } }catch (Exception ex) { ex.printStackTrace(); } String string = str.toString();return string;
}

java如何通过client客戶端http实现get/ post请求传递json参数到restful 服务接口相关推荐

  1. webso员ket php,客戶端和PHP後端通信:Sokets,Stream,TCP/UDP?

    簡短版本:我想將客戶端連接到PHP服務器,但是我同時運行10個PHP腳本的服務器的限制.客戶端和PHP後端通信:Sokets,Stream,TCP/UDP? 的問題是:什麼是連接與PHP腳本客戶的最佳 ...

  2. c#(服务器)与java(客户端)通过socket传递对象_C#(服務器)與Java(客戶端)通過Socket傳遞對象...

    最近做項目,需要C#與java間的交互,也就是C#編寫服務器,java編寫客戶端,讓兩者進行通信. 通信無非就是互發數據,首選Socket技術,通過TCP協議建立長連接,一般是以字節數組的形式傳遞數據 ...

  3. 配置Git服務器和Windows客戶端

    按照這位仁兄的方法(http://www.fwolf.com/blog/post/429)配置好Ubuntu的GIT服務後,基本上都在Linux下面使用沒有問題了.但在Windows客戶端怎麼辦呢?還 ...

  4. app inventor HTML5,[App Inventor] Web客戶端元件 POST 傳值的使用方式

    過去在開發App時,Web客戶端元件大部份都以Get的方式進行值的傳遞.那可以用POST嗎?以下簡單的範例,我們將使用Web客戶端元件以POST的方式傳值給一個PHP程式,然後再返回結果顯示在App中 ...

  5. c#服务器上的文件怎么打印,C# 如何調用客戶端打印機打印服務器上的word文件

    [size=13px]    做了一個系統,需要打印word,服務器上有打印模塊,打印之前是將打印的內容通過書簽的新式生成了一個新的word保存在服務器上,在客戶端訪問系統打印的時候出現了一些問題.客 ...

  6. 刪除已存儲在SVN客戶端的账号与密…

    1. Windows下      使用TortoiseSVN的svn客戶端工具,点击右鍵,打开下图,   选择setting,打开下对话框,并点击Saved Date     根据对话框右边的提示信息 ...

  7. android post json格式,Android中post请求传递json数据给服务端的实例

    在最近的项目中有个需求是这样的: 入参封装成JSON,EXAMPLE: { "uuid": "iamauuid","clientType": ...

  8. android json传输数据到服务器,Android中post请求传递json数据给服务端的实例

    在最近的项目中有个需求是这样的: 入参封装成JSON,EXAMPLE: { "uuid": "iamauuid", "clientType" ...

  9. java ftp客戶端

    最近打算做一个android上的ftp客户端工具,网上搜索了一下,发现apache commons-net可以很方便的实现,但是这个第三方包中对文件夹的删除与创建(级联)操作并不是特别的方便.删除文件 ...

最新文章

  1. python基础教程 下载-Python基础教程第3版中国PDF电子书免费下载
  2. 图像处理(四)图像分割(2)测地距离Geodesic图割
  3. View和View的参数传递
  4. jQuery 库 - 特性
  5. tcp当主动发出syn_一文读懂TCP四次挥手工作原理及面试常见问题汇总
  6. 数据结构:二分查找python实现
  7. mvc @html.editorfor,在MVC中,@Html.EditorFor(m = ( )_CSharp_开发99编程知识库
  8. leetcode 152 乘积最大子序列
  9. matlab s函数_matlab结构体 rmfield,arrayfun,structfun,struct2cell,cell2struct
  10. 专访iQOO Pro产品经理:以更好的产品 更低的价格推进5G生态普及
  11. Fit项目分页组件的编写
  12. 理解 Redux 的最好方式,是自己写一个
  13. 单调队列:temperature
  14. 通过napalm-huawei-vrp模块对华为交换机信息进行分析(ENSP模拟器)
  15. 视频监控市场发展潜力大 六个阻碍待突破
  16. eNSP 华为模拟器更新说明
  17. OD 手动脱壳 - UPX
  18. Scrapy爬取淘宝网数据的尝试
  19. 网页前端设计一般思路
  20. ISA防火墙基础及应用

热门文章

  1. 概率分布之二项分布、泊松分布
  2. c语言判断是否以某个字符串开头,以某个字符串结尾
  3. wasc honeypot
  4. vue router.beforeEach(),详解
  5. AutoLeaders控制组——51单片机学习笔记(DS18B20温度传感器、LCD1602、直流电机+PWM)
  6. MFC - LNK2001 “无法解析的外部符号”的几种情况及解决办法
  7. 使用ListIterator 对List遍历时修改,删除
  8. HDU-5868-Different Circle Permutation(快速幂求fib,单数欧拉函数(1e9规模),oeis)...
  9. MATLAB(2)--MATLAB矩阵的表示
  10. 如何查看vue打印的console.log日志