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的示例的更多相关文章

  1. 明确出需求 然后开会评审 要什么接口 接口参数、返回json内容、格式 协定好 在做

     明确出需求 然后开会评审 要什么接口 接口参数.返回json内容.格式 协定好 在做 

  2. CloseableHttpClient方式配置代理服务器访问外网

    小编最近在负责银行内部项目.其中有模块需要访问天眼查API接口,但由于公司全部内网,所以需要配置代理服务器才可以访问外网接口. 又到了激动人心的上码时刻! public void Connect(Ht ...

  3. 1 Openwrt无线中继设置并访问外网

    https://www.cnblogs.com/wsine/p/5238465.html 配置目标 主路由器使用AP模式发射Wifi 从路由器使用Client模式接受Wifi 从路由器使用Master ...

  4. Neutron:访问外网

    instance 如何与外部网络通信?   这里的外部网络是指的租户网络以外的网络.  租户网络是由 Neutron 创建和维护的网络. 外部网络不由 Neutron 创建. 如果是私有云,外部网络通 ...

  5. Openwrt无线中继设置并访问外网

    Openwrt无线中继设置并访问外网 本篇博文参考来自:http://blog.csdn.net/pifangsione/article/details/13162023 配置目标 主路由器使用AP模 ...

  6. 虚机中访问外网;NAT中的POSTROUTING是怎么搞的?

    看下docker中是怎么配置的网络 在虚机中访问外网:设定了qemu,在主机上添加路由:sudo iptables -t nat -I POSTROUTING -s 192.168.1.110 -j ...

  7. OpenStack创建网络和虚拟机、dhcp设备、虚拟路由器、虚拟机访问外网原理分析

    创建网络和虚拟机流程: 1.创建网络和子网 背后发生了什么: Neutron让控制节点上针对此子网的dhcp(虚拟设备)启动,用于给该子网下的实例分配ip 2.生成虚拟机 背后发生了什么: 用户通过G ...

  8. iptables内网访问外网 ε=ε=ε=(~ ̄▽ ̄)~

    介绍 iptables概述: netfilter/iptables : IP信息包过滤系统,它实际上由两个组件netfilter 和 iptables 组成. netfilter/iptables 关 ...

  9. 6.DNS公司PC访问外网的设置 + 主DNS服务器和辅助DNS服务器的配置

    网站部署之~Windows Server | 本地部署 http://www.cnblogs.com/dunitian/p/4822808.html#iis DNS服务器部署不清楚的可以看上一篇:ht ...

随机推荐

  1. <转>libjpeg解码内存中的jpeg数据

    转自http://my.unix-center.net/~Simon_fu/?p=565 熟悉libjpeg的朋友都知道libjpeg是一个开源的库.Linux和Android都是用libjpeg来 ...

  2. cf591A Wizards' Duel

    A. Wizards' Duel time limit per test 2 seconds memory limit per test 256 megabytes input standard in ...

  3. 五子棋——C++

    最近在学C++,这个是照葫芦画瓢的五子棋C++版- - 依赖SDL_PingGe_1.3,很多实用的函数,类我都封装成DLL了调用起来真是舒服啊.. 不过一方面要对DLL做测试,一方面要开发,一个人还 ...

  4. compile libvirt

    POSIX-linux 编译安装libvirt依赖包; 1.yum install device-mapper-devel

  5. java中的接口和抽象类是什么?

    抽象类与接口的区别 abstract class和interface是Java语言中对于抽象类定义进行支持的两种机制,正是由于这两种机制的存在,才赋予了Java强大的面向对象能力.abstract c ...

  6. C++ —— 编译程序

    目录: 0.GCC online documentation 1.gcc编译器 常用命令 2.VC编译器  常用参数说明 3.C预处理器命令说明 4.debug 和 release 的区别 0.GCC ...

  7. sql server 扩展存储过程

    C# 代码 using Microsoft.SqlServer.Server; using System; using System.Collections.Generic; using System ...

  8. js获取当前页面的url中id

    function UrlSearch() { var name, value; var str = location.href; //获取到整个地址 var num = str.indexOf(&qu ...

  9. 安装VS2012 update3提示缺少Microsoft根证书颁发机构2010或2011的解决方法

    警告提示如图: (copy的百度贴吧的童鞋的截图) 解决方法: 下载2010.10或2011.10的根证书即可 直通车:http://maxsky.ys168.com/ ——05.||浮云文件||—— ...

  10. layout布局实例化

    实例化xml中的Layout布局在开发中经常会用到,有几种方法可以使用 1.在Activity中使用getLayoutInflater()方法 View layout = getLayoutInfla ...