(封装get-Post)访问HTTP 接口1
来源:互联网 发布:超级搜索软件 编辑:程序博客网 时间:2024/06/03 12:52
public static String SMS_GATEWAY_URL = "http://localhost:9090/sms_service/sms";//网关public static SKResult deleteSign(String id){Map<String, String> requestMap = new HashMap<String, String>();requestMap.put("id", id);String requestJson = JSONUtils.toJSONString(requestMap);//map转JSON的另一种方法链接SKResult sk = HttpUtils.doPost(Constants.SMS_GATEWAY_URL+"2002", requestJson, "utf-8");if(sk.isResult()){// 请求成功Map<String, Object> resultMap = (Map<String, Object>) JSONUtils.parse(sk.getObj().toString());if("0000".equals(resultMap.get("ret_code"))){Map<String, Object> map = new HashMap<String, Object>();Map<String, Object> obj = (Map<String, Object>) resultMap.get("obj");int result = (int)(double)obj.get("result");String msg = obj.get("msg")==null?null:(String)obj.get("msg");map.put("ret_result", result);map.put("ret_msg", msg);if(result == 0){return new SKResult(true, "", map);}else{return new SKResult(false, obj.get("errmsg").toString());}}else{return new SKResult(false, "系统异常,请稍后重试");}}else{// 请求失败return new SKResult(false, "系统异常,请稍后重试");}}
<!-- httpclient --><dependency><groupId>commons-httpclient</groupId><artifactId>commons-httpclient</artifactId><version>3.1</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.3.4</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpmime</artifactId><version>4.2.5</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient-osgi</artifactId><version>4.3.4</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient-cache</artifactId><version>4.2.5</version></dependency>
import java.io.IOException;import java.io.UnsupportedEncodingException;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.ParseException;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;public class HttpUtils{/** * 发送http post json数据请求 * @param url * @param reqstr json 格式,可通过map组装参数转换为json * @return */public static SKResult doPost(String url, String reqstr, String charset){System.out.println(String.format("请求URL:%s", url));System.out.println(String.format("请求数据:%s", reqstr));HttpClient httpClient = HttpClients.createDefault();HttpPost httpPost = new HttpPost(url);try {StringEntity s = new StringEntity(reqstr,charset);s.setContentEncoding(charset);s.setContentType("application/json");httpPost.setEntity(s);HttpResponse httpResponse = httpClient.execute(httpPost);int statusCode = httpResponse.getStatusLine().getStatusCode();if(statusCode==HttpStatus.SC_OK){//org.apach.http// 请求成功System.out.println("请求成功");String responseStr = EntityUtils.toString(httpResponse.getEntity(), charset);System.out.println(String.format("返回数据:%s", responseStr));return new SKResult(true, "请求成功", responseStr);}else{// 请求失败System.out.println("请求失败");return new SKResult(false, String.format("请求失败[%d-%s]", statusCode, httpResponse.getStatusLine().getReasonPhrase()));}} catch (UnsupportedEncodingException e) {e.printStackTrace();return new SKResult(false, "请求参数格式错误");} catch (ClientProtocolException e) {e.printStackTrace();return new SKResult(false, "请求异常");} catch (ParseException e) {e.printStackTrace();return new SKResult(false, "返回数据解析异常");} catch (IOException e) {e.printStackTrace();return new SKResult(false, "网络异常");}} /** * 向指定URL发送GET方法的请求 * * @param url * 发送请求的URL * @param param * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return URL 所代表远程资源的响应结果 */ public static String sendGet(String url) { String result = ""; BufferedReader in = null; try { String urlNameString = url; URL realUrl = new URL(urlNameString); // 打开和URL之间的连接 URLConnection connection = realUrl.openConnection(); // 设置通用的请求属性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 建立实际的连接 connection.connect(); // 获取所有响应头字段// Map<String, List<String>> map = connection.getHeaderFields(); // 遍历所有的响应头字段// for (String key : map.keySet()) {// System.out.println(key + "--->" + map.get(key));// } // 定义 BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader( connection.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("发送GET请求出现异常!" + e); e.printStackTrace(); } // 使用finally块来关闭输入流 finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } System.out.println(result); return result; }}
----------------------------------------------------------------分割线------------------------------------------------------------
package com.impay.smsmer.domain;/** * * @author zhouy * */public class SKResult {// 状态private boolean result;// 信息private String respMsg;// 对象private Object obj;public SKResult(boolean result, String respMsg) {super();this.result = result;this.respMsg = respMsg;}public SKResult(boolean result, String respMsg, Object obj) {super();this.result = result;this.respMsg = respMsg;this.obj = obj;}public boolean isResult() {return result;}public void setResult(boolean result) {this.result = result;}public String getRespMsg() {return respMsg;}public void setRespMsg(String respMsg) {this.respMsg = respMsg;}public Object getObj() {return obj;}public void setObj(Object obj) {this.obj = obj;}@Overridepublic String toString() {return "SKResult [result=" + result + ", respMsg=" + respMsg + ", obj="+ obj + "]";}}
阅读全文
0 0
- (封装get-Post)访问HTTP 接口1
- HTTP请求接口方法(POST/GET)
- iOS http访问post 、get
- (封装xml)访问HTTP 接口2
- HttpClient测试接口的封装(get和post)
- 纯C++实现的HTTP请求封装(POST/GET)
- restful接口实现跨域访问,以及get请求对象参数对象封装,post请求
- VC++ Http Get Post封装类
- 【No9.】完美封装Http请求 Get、Post
- HttpClient封装POST,GET方式HTTP请求
- Qt--Http请求封装(Get Post)
- Qt--Http请求封装(Get Post)
- Qt--Http请求封装(Get Post)
- get post方式访问webservice中的get post接口
- http跨平台访问接口的post,get,及文件上传方式工具类(httpClient)
- http请求远程接口获得JSON数据(1) --- 利用HttpURLConnection发送post/get请求
- get/post方式调用http接口
- get/post方式调用http接口
- 漫谈 JVM 内存分代、垃圾回收
- 百度地图java.lang.UnsatisfiedLinkError: No implementation found for int
- SlidingBall水平切换图片无限循环
- Java学习之线程池
- react路由学习网站
- (封装get-Post)访问HTTP 接口1
- 表格、text文本域
- VMWare虚拟机三种网络模式的简介
- Android开发之--安卓原生与h5交互-基础篇
- 远程(局域网)链接windows桌面
- PLSQL中&符号处理
- 这是一篇最通熟易懂的Hadoop HDFS实践攻略
- TensorFlow学习笔记(9)--使用CNN做英文文本分类任务
- BestCoder Round #59 (div.1)