一个用httpPost,get访问外网接口,参数json,返回json的示例
package com.royal.util;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import net.sf.json.JSONObject;
import org.apache.catalina.User;
import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import com.royal.entity.AccessToken;
import com.royal.entity.OAuthAccessToken;
import com.royal.entity.UserInfo;
import com.royal.menu.Button;
import com.royal.menu.ClickButton;
import com.royal.menu.Menu;
import com.royal.menu.ViewButton;
import com.royal.po.ActionInfo;
import com.royal.po.QuickMark;
import com.royal.po.SceneInfo;
@SuppressWarnings("deprecation")
public class WeiXinUtil {
public static final String GRANT_TYPE = "authorization_code";
public static final String USER_INFO_URL = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
public static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
public static final String SEND_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
public static final String CREATE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
public static final String UPLOAD_URL = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
public static final String JSTICKET = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN";
// OAuth2.0 使用接口地址
public static final String RETURN_URL = "http://m2m.tunnel.qydev.com/weinx/oauth.do";// 回调地址
public static final String OAUTH_RETURN_CODE = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=RETURN_URL&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";// 获取code标识
public static final String OAUTH_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";// OAUTH2.0获取openid
public static final String OAUTH_USER_INFO = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";// OAUTH2.0获取用户详细信息
public static JSONObject doGetStr(String url) {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
JSONObject jsonObject = null;
try {
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity, "utf-8");
jsonObject = JSONObject.fromObject(result);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonObject;
}
public static JSONObject doPostStr(String url, String outStr) {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
JSONObject jsonObject = null;
try {
httpPost.setEntity(new StringEntity(outStr, "utf-8"));
HttpResponse response = httpClient.execute(httpPost);
String result = EntityUtils.toString(response.getEntity(), "utf-8");
jsonObject = JSONObject.fromObject(result);
} catch (Exception e) {
e.printStackTrace();
}
return jsonObject;
}
public static AccessToken getAccessToken() {
AccessToken accessToken = new AccessToken();
JSONObject accessTokenObj = doGetStr(
ACCESS_TOKEN_URL.replace("APPID", TokenThread.appid).replace("APPSECRET", TokenThread.appsecret));
if (null != accessTokenObj) {
accessToken.setAccess_token(accessTokenObj.getString("access_token"));
accessToken.setExpires_in(accessTokenObj.getInt("expires_in"));
}
return accessToken;
}
/***
* OAuth2.o 方法
*/
public static OAuthAccessToken getOauthAccessToken(String code) {
OAuthAccessToken token = new OAuthAccessToken();
JSONObject obj = WeiXinUtil.doGetStr(OAUTH_URL.replace("APPID", TokenThread.appid)
.replace("SECRET", TokenThread.appsecret).replace("CODE", code));
if (obj != null) {
try {
token.setAccessToken(obj.getString("access_token"));
token.setRefresh_token(obj.getString("refresh_token"));
token.setOpenid(obj.getString("openid"));
} catch (Exception e) {
return null;
}
}
return token;
}
/***
* OAuth2.o 方法
*/
public static UserInfo getSNSUserInfo(String accessToken, String openid) {
UserInfo userInfo = new UserInfo();
JSONObject obj = doGetStr(OAUTH_USER_INFO.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openid));
if (obj != null) {
userInfo.setOpenid(openid);
userInfo.setNickname(obj.getString("nickname"));
}
return userInfo;
}
public static String getUserName(String accessToken, String openID) {
String name = "";
JSONObject userInfoObj = doGetStr(USER_INFO_URL.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openID));
if (null != userInfoObj) {
name = userInfoObj.getString("nickname");
}
return name;
}
public static boolean isValid(UserInfo userInfo){
boolean flag=false;
Map<String, String> map=getUser();
String nickName=userInfo.getNickname();
for (Map.Entry<String, String> entry : map.entrySet()) {
if(entry.getValue().equals(nickName)){
flag = true;
break;
}
}
return flag;
}
public static Map<String, String> getUser(){
Map<String, String> map = new HashMap<>();
map.put("1 ", "王老爷-王赟");
map.put("2", "高翔");
map.put("3", "cici");
map.put("4", "Andy");
map.put("5", "方捷");
map.put("6", "罗毅平");
map.put("7", "霨霨");
map.put("8", "絆");
return map;
}
/**
* 获取jsticket
*
* @return
*/
public static String getJsTicket(String accessToken) {
JSONObject json = doGetStr(JSTICKET.replace("ACCESS_TOKEN", accessToken));
String Jsticket="";
if (null != json) {
Jsticket = json.getString("ticket");
}
return Jsticket;
}
/**
* 得到请求的url和参数
* */
public static String getFullURL(HttpServletRequest request) {
StringBuffer url = request.getRequestURL();
if (request.getQueryString() != null) {
url.append("?");
url.append(request.getQueryString());
}
return url.toString();
}
/***
*
* @return
* @author :xuyan
* @date :2015-9-12
* @Description:创建菜单 Menu
*/
public static Menu initMenu() {
Menu menu = new Menu();
// 一栏 二级菜单
ClickButton button11 = new ClickButton();
button11.setType("click");
button11.setName("IT软件外包");
button11.setKey("ITSoft");
ClickButton button12 = new ClickButton();
button12.setType("click");
button12.setName("IT业务外包");
button12.setKey("ITService");
ClickButton button13 = new ClickButton();
button13.setType("click");
button13.setName("IT人力外包");
button13.setKey("humanOut");
// 二栏 二级菜单
ClickButton button21 = new ClickButton();
button21.setType("click");
button21.setName("招贤纳士");
button21.setKey("joinus");
ClickButton button22 = new ClickButton();
button22.setType("click");
button22.setName("品牌文化");
button22.setKey("brandCulture");
ClickButton button23 = new ClickButton();
button23.setType("click");
button23.setName("渠道合作");
button23.setKey("channelJoin");
// 三栏 二级菜单
ClickButton button31 = new ClickButton();
button31.setName("在线咨询");
button31.setType("click");
button31.setKey("online");
ViewButton button32 = new ViewButton();
button32.setName("满意度调研");
button32.setType("view");
// String url = OAUTH_RETURN_CODE.replace("APPID",
// TokenThread.appid).replace("", RETURN_URL);
String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx4bfd05f8e3b2404c&redirect_uri=http://www.m2m.cn/weinx/oauth.do&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";// 获取code标识
System.out.println("url=" + url);
button32.setUrl(url);
// ClickButton button32= new ClickButton();
// button32.setType("click");
// button32.setName("问卷调研");
// button32.setKey("investigation");
// 一栏 一级菜单
Button button1 = new Button();
button1.setName("皇家服务");
button1.setSub_button(new Button[] { button11, button12, button13 });
// 二栏 一级菜单
Button button2 = new Button();
button2.setName("皇家品牌");
button2.setSub_button(new Button[] { button21, button22, button23 });
// 三栏 一级菜单
Button button3 = new Button();
button3.setName("我的皇家");
button3.setSub_button(new Button[] { button31, button32 });
menu.setButton(new Button[] { button1, button2, button3 });
return menu;
}
// 创建菜单
public static int creatMenu(String token, String menu) {
int result = 0;
String url = CREATE_MENU_URL.replace("ACCESS_TOKEN", token);
JSONObject jsonObject = doPostStr(url, menu);
if (jsonObject != null) {
result = jsonObject.getInt("errcode");
}
return result;
}
// 创建二维码
public static String quickmark(String token) {
String ticket = "";
String address = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN";
String url = address.replace("TOKEN", token);
QuickMark mark = new QuickMark();
SceneInfo info = new SceneInfo();
info.setScene_str("123");
ActionInfo actionInfo = new ActionInfo();
actionInfo.setScene(info);
mark.setAction_name("QR_LIMIT_SCENE");
mark.setAction_info(actionInfo);
String canshu = JSONObject.fromObject(mark).toString();
JSONObject jsonObject = doPostStr(url, canshu);
if (jsonObject != null) {
// ticket = jsonObject.getString("ticket");
ticket = jsonObject.getString("url");
}
return ticket;
}
public static String upload(String filePath, String accessToken, String type) {
File file = new File(filePath);
if (!file.exists() || !file.isFile()) {
try {
throw new IOException("文件不存在");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String url = UPLOAD_URL.replace("ACCESS_TOKEN", accessToken).replaceAll("TYPE", type);
URL urlObj;
HttpURLConnection con;
String result = null;
try {
urlObj = new URL(url);
con = (HttpURLConnection) urlObj.openConnection();
con.setRequestMethod("post");
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
// 设置请求头信息
con.setRequestProperty("connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
// 设置边界
String BOUNDARY = "---------" + System.currentTimeMillis();
con.setRequestProperty("Content-Type", "multipart/from-data;boundary=" + BOUNDARY);
StringBuffer sb = new StringBuffer();
sb.append("--");
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition:form-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] head = sb.toString().getBytes("utf-8");
// 获得输出流
OutputStream out = new DataOutputStream(con.getOutputStream());
out.write(head);
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
// 结尾部分
byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");
out.write(foot);
out.flush();
out.close();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
reader.close();
if (result == null) {
result = buffer.toString();
}
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
JSONObject jsonObj = JSONObject.fromObject(result);
System.out.println(jsonObj);
String mediaId = jsonObj.getString("media_id");
return mediaId;
}
}
一个用httpPost,get访问外网接口,参数json,返回json的示例的更多相关文章
- 明确出需求 然后开会评审 要什么接口 接口参数、返回json内容、格式 协定好 在做
明确出需求 然后开会评审 要什么接口 接口参数.返回json内容.格式 协定好 在做
- CloseableHttpClient方式配置代理服务器访问外网
小编最近在负责银行内部项目.其中有模块需要访问天眼查API接口,但由于公司全部内网,所以需要配置代理服务器才可以访问外网接口. 又到了激动人心的上码时刻! public void Connect(Ht ...
- 1 Openwrt无线中继设置并访问外网
https://www.cnblogs.com/wsine/p/5238465.html 配置目标 主路由器使用AP模式发射Wifi 从路由器使用Client模式接受Wifi 从路由器使用Master ...
- Neutron:访问外网
instance 如何与外部网络通信? 这里的外部网络是指的租户网络以外的网络. 租户网络是由 Neutron 创建和维护的网络. 外部网络不由 Neutron 创建. 如果是私有云,外部网络通 ...
- Openwrt无线中继设置并访问外网
Openwrt无线中继设置并访问外网 本篇博文参考来自:http://blog.csdn.net/pifangsione/article/details/13162023 配置目标 主路由器使用AP模 ...
- 虚机中访问外网;NAT中的POSTROUTING是怎么搞的?
看下docker中是怎么配置的网络 在虚机中访问外网:设定了qemu,在主机上添加路由:sudo iptables -t nat -I POSTROUTING -s 192.168.1.110 -j ...
- OpenStack创建网络和虚拟机、dhcp设备、虚拟路由器、虚拟机访问外网原理分析
创建网络和虚拟机流程: 1.创建网络和子网 背后发生了什么: Neutron让控制节点上针对此子网的dhcp(虚拟设备)启动,用于给该子网下的实例分配ip 2.生成虚拟机 背后发生了什么: 用户通过G ...
- iptables内网访问外网 ε=ε=ε=(~ ̄▽ ̄)~
介绍 iptables概述: netfilter/iptables : IP信息包过滤系统,它实际上由两个组件netfilter 和 iptables 组成. netfilter/iptables 关 ...
- 6.DNS公司PC访问外网的设置 + 主DNS服务器和辅助DNS服务器的配置
网站部署之~Windows Server | 本地部署 http://www.cnblogs.com/dunitian/p/4822808.html#iis DNS服务器部署不清楚的可以看上一篇:ht ...
随机推荐
- java二进制文件复制
package com.starain.io; import java.io.BufferedInputStream;import java.io.BufferedOutputStream;impor ...
- [置顶] Putty管理私钥文件
openssh中,ssh_keygen产生的私钥,id_rsa这种密钥putty是不认识的,必须先把它转换成ppk格式, Windows上如果你安装了git,它里面bin目录下就有ssh_keygen ...
- FSharp.Data 程序集之 Http
FSharp.Data 程序集之 Http (** # F# Data: HTTP Utilities .NET 库提供了强大的 API,产生和发送 HTTP WEB 请求,有两个类型,一个简单,`W ...
- Effective C++ 第二版 40)分层 41)继承和模板 42)私有继承
条款40 通过分层来体现"有一个"或"用...来实现" 使某个类的对象成为另一个类的数据成员, 实现将一个类构筑在另一个类之上, 这个过程称为 分层Layeri ...
- Core Services 层
Core Services层为所有的应用程序提供基础系统服务.可能应用程序并不直接使用这些服务,但它们是系统很多部分赖以建构的基础. 高阶特性 下面的部分描述一些比较常见特性,也许您正打算让您的应用程 ...
- 如何为Myeclipse手工添加dtd支持
一.引言 在MyEclipse中开发三大框架的项目时候经常会写一些配置的xml文件,例如:Struts2的struts.xml和Hibernate的hibernate.cfg.xml.Spring的a ...
- 基于Android Volley的网络请求工具
基于Android Volley的网络请求工具. 一.说明 AndroidVolley,Android Volley核心库及扩展工程.AndroidVolleySample,网络请求工具示例工程.Re ...
- Android组件间的数据传输
组件我们有了,那么我们缺少一个组件之间传递信息的渠道.利用Intent做载体,这是一个王道的做法.还有呢,可以利用文件系统来做数据共享.也可以使用Application设置全局数据,利用组件来进行控制 ...
- Configuring Network Configuration-RHEL7
1.查看网络状态systemctl status NetworkManager You can use the systemctl status NetworkManager command to ...
- vipw和vigr命令
Modifying the Configuration Files To add user accounts, it suffices that one line is added to /etc/p ...