关闭

通过http获取资源

312人阅读 评论(0) 收藏 举报

法一(推荐):

public static String getHttpPost(String url, String params) {

String result = "";
HttpPost httppost = new HttpPost(url);
StringEntity entity = new StringEntity(params, ContentType.create("application/json", Consts.UTF_8));
entity.setChunked(true);
httppost.setEntity(entity);
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response;
try {
response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() == 200) {
result = EntityUtils.toString(response.getEntity(), "UTF-8");
} else {
result = "[返回失败!]";
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;

}

法二:

public static String getMes(String url, String params) {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost htPost = new HttpPost(url);
String backMes = null;
try {
htPost.setHeader("content-type", "application/json");
StringEntity reqEntity = new StringEntity(params);
htPost.setEntity(reqEntity);
HttpResponse httpResponse = client.execute(htPost);
HttpEntity entity = httpResponse.getEntity();
backMes = EntityUtils.toString(entity, "UTF-8").toString();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
client.close();
client = null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return backMes;
}


*应用:生成二维码(框架:playframework,数据库:mongodb)

接口

/**
* 创建临时二维码ticket

* @param access_token
* @return
* @throws Exception
*/
public String getJsapi_ticket_WeixinLs(Long manageQRcodeId) throws Exception {
String jsapi_ticket = "";
CloseableHttpClient httpclient = HttpClients.createDefault();
try {


HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + getCacheAccessToken());


JSONObject jsonObj = new JSONObject();
JSONObject scene = new JSONObject();
JSONObject action_info = new JSONObject();


jsonObj.put("action_name", "QR_SCENE");
jsonObj.put("expire_seconds", 604800);
scene.put("scene_id", manageQRcodeId);
action_info.put("scene", scene);
jsonObj.put("action_info", action_info);


/*
* jsonObj.put( "action_info", new JSONObject().put("scene", new JSONObject().put("scene_id", manageQRcodeId)));
*/


StringEntity entity = new StringEntity(jsonObj.toString(), "UTF-8");


httpPost.setEntity(entity);


CloseableHttpResponse response1 = httpclient.execute(httpPost);
try {


HttpEntity httpEntity = response1.getEntity();


if (httpEntity != null) {
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpEntity.getContent(), "UTF-8"), 8 * 1024);
StringBuilder entityStringBuilder = new StringBuilder();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
entityStringBuilder.append(line);
}
// 利用从HttpEntity中得到的String生成JsonObject
// resultJsonObject = new
// JSONObject(entityStringBuilder.toString());


JSONObject dataJson = JSONObject.fromObject(entityStringBuilder.toString());
jsapi_ticket = dataJson.get("ticket") + "";
} catch (Exception e) {
e.printStackTrace();
}
}


} finally {
response1.close();
}
} finally {
httpclient.close();
}
return jsapi_ticket;


}


/**
* 创建永久二维码ticket

* @param manageQRcodeId
* @return
* @throws Exception
*/
public String getJsapi_ticket_WeixinGd(Long manageQRcodeId) throws Exception {
String jsapi_ticket = "";
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + getCacheAccessToken());


JSONObject jsonObj = new JSONObject();
JSONObject action_info = new JSONObject();
JSONObject scene = new JSONObject();
jsonObj.put("action_name", "QR_LIMIT_SCENE");
scene.put("scene_id", manageQRcodeId);
action_info.put("scene", scene);


jsonObj.put("action_info", action_info);


System.out.println(jsonObj.toString());


StringEntity entity = new StringEntity(jsonObj.toString(), "UTF-8");


httpPost.setEntity(entity);


CloseableHttpResponse response1 = httpclient.execute(httpPost);
try {


HttpEntity httpEntity = response1.getEntity();


if (httpEntity != null) {
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpEntity.getContent(), "UTF-8"), 8 * 1024);
StringBuilder entityStringBuilder = new StringBuilder();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
entityStringBuilder.append(line);
}
// 利用从HttpEntity中得到的String生成JsonObject
JSONObject dataJson = JSONObject.fromObject(entityStringBuilder.toString());
jsapi_ticket = dataJson.get("ticket") + "";
} catch (Exception e) {
e.printStackTrace();
}
}


} finally {
response1.close();
}
} finally {
httpclient.close();
}
return jsapi_ticket;


}

调用

public static Result createChannelPic(String channelNo) {
// 生成返回的json对象
ObjectNode repnode = Json.newObject();
DBCollection coll = MongoManager.getDB("").getCollection("channel_manager");


DBObject query = new BasicDBObject("channel_no", channelNo).append("is_enable", 1);


DBObject channel = coll.findOne(query);
repnode.put("status", 1);
repnode.put("msg", "二维码生成成功!");
if (channel == null) {
repnode.put("status", 0);
repnode.put("msg", "渠道信息不存在!");
} else {
// 获取存放二维码地址
String upload_user_channel = Play.application().configuration().getString("upload_user_channel");
upload_user_channel += channelNo + ".jpg";


Long cn = Long.parseLong(channelNo);


// 获取生产二维码的工具类
QRHttpClient client = QRHttpClient.getInstance();
try {
String ticket = client.getJsapi_ticket_WeixinGd(cn);
client.getticketImage(URLEncoder.encode(ticket, "UTF-8"), upload_user_channel);


// 保存数据到数据库
DBObject o = new BasicDBObject();
o.put("qr_path", upload_user_channel);
o.put("ticket", ticket);
o.put("update_date", new Date());
coll.update(query, new BasicDBObject("$set", o), true, false);


} catch (Exception e) {
repnode.put("status", 0);
repnode.put("msg", "生成失败,请稍后再试!");
}


}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:45525次
    • 积分:943
    • 等级:
    • 排名:千里之外
    • 原创:59篇
    • 转载:12篇
    • 译文:1篇
    • 评论:3条
    文章分类
    最新评论