httpClient发送get请求调用接口
2016-12-21 11:32
609 查看
最近在项目中需要调用外部的接口,开始用的httpurl来写,后来发现httpClient相比更简单,现在将2种方法记录下来:
首先加入httpClient的maven依赖: <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency>
通过HttpURLConnection实现:
public String getNonce(String username) { String url = "http://xxxxxx/lock/createNonce?name=" + username; JSONObject jsonObject = null; StringBuilder json = new StringBuilder(); String nonce = null; try { URL getUrl = new URL(url); // 返回URLConnection子类的对象 HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection(); // 连接 connection.connect(); InputStream inputStream = connection.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8"); // 使用Reader读取输入流 BufferedReader reader = new BufferedReader(inputStreamReader); String lines; while ((lines = reader.readLine()) != null) { json.append(lines); } reader.close(); // 断开连接 connection.disconnect(); //将字符串转为json格式 jsonObject = JSONObject.fromObject(json.toString()); nonce = jsonObject.get("nonce").toString(); } catch (IOException ioException) { ioException.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return nonce; }
HttpClient方式
public String getNonce(String username) { String url = "http://xxxx/lock/createNonce?name=" + username; JSONObject jsonObject = null; String nonce = null; //发送get请求 CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpGet httpGet = new HttpGet(url); CloseableHttpResponse response = httpClient.execute(httpGet); try { //获取响应实体 HttpEntity entity = response.getEntity(); if (entity != null) { String content = EntityUtils.toString(entity); jsonObject = JSONObject.fromObject(content); nonce = jsonObject.get("nonce").toString(); } } finally { response.close(); } } catch (IOException ioException) { ioException.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } return nonce; }
相关文章推荐
- java HttpClient get post请求 调用接口
- C#通过发送 http 请求调用接口之Get
- HttpClient 发送post和get请求 调用第三方webservice
- 我的Android进阶之旅------>Android发送GET和POST以及HttpClient发送POST请求给服务器响应
- 调用webapi 错误:使用 HTTP 谓词 POST 向虚拟目录发送了一个请求,而默认文档是不支持 GET 或 HEAD 以外的 HTTP 谓词的静态文件。的解决方案
- cocos2d-x httpclient发送get或者post消息请求
- httpclient post get请求调用
- java apache commons HttpClient发送get和post请求的学习整理
- 关于HttpClient发送get请求自动处理302状态码
- java apache commons HttpClient发送get和post请求的学习整理
- java apache commons HttpClient发送get和post请求的学习整理
- python通过http请求发送soap报文进行webservice接口调用
- java发送post和get请求(1)---HttpClient 方式
- Android使用Apache HttpClient发送GET、POST请求
- [Socket]利用Jatarka下HttpClient发送(Get && Post)请求
- 我的Android进阶之旅------>Android发送GET和POST以及HttpClient发送POST请求给服务器响应
- java HttpUrlConnection get和post 模拟请求 调用接口
- java httpclient发送post get 请求
- Android下通过httpClient发送GET和POST请求
- [Socket]利用Android下的HttpClient发送GET && POST请求