一个用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;
}
}

上一篇:C#后台调用Http外网接口(GET, POST)


下一篇:iptables 思维导图 (zz)