浅谈Java代码的 微信长链转短链接口使用 post 请求封装Json(实例)
废话不多说,直接上代码
StringlongUrl="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+MpUtil.APPID+"&redirect_uri="+MpUtil.HOMEPAGE+"/nweixinLoginPc.fo%3Frandomcode="+randomcode+"&response_type=code&scope=snsapi_userinfo&state=account#wechat_redirect";//什么不重要,自己的长链 StringaccessToken=MpUtil.getAccessToken(MpUtil.APPID,MpUtil.APPSECRET); StringshortUrl=null;//短连接地址,生成二维码用,识别快 StringhttpUrl="https://api.weixin.qq.com/cgi-bin/shorturl?access_token="+accessToken;//此处访问微信短链方法 /** *调用举例 curl-d"{\"action\":\"long2short\", \"long_url\":\"http://wap.koudaitong.com/v2/showcase/goods?alias=128wi9shh&spm=h56083&redirect_count=1\"}" "https://api.weixin.qq.com/cgi-bin/shorturl?access_token=ACCESS_TOKEN" */ JSONObjectjsonObject=newJSONObject(); jsonObject.put("action","long2short"); jsonObject.put("long_url",longUrl); StringtransJson=jsonObject.toString()+httpUrl; RequestEntityse=newStringRequestEntity(transJson,"application/json","UTF-8"); //微信返回的字符串 //成功{"errcode":0,"errmsg":"ok","short_url":"http:\/\/w.url.cn\/s\/AvCo6Ih"} //失败{"errcode":40013,"errmsg":"invalidappid"} StringresultsString=post(jsonObject,httpUrl);//封装的post方法 StringshortUrl=MpUtil.getJsonValue(resultsString,"short_url");//得到的短链 ?12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849publicstaticStringpost(JSONObjectjson,StringURL){HttpClientclient=newDefaultHttpClient();HttpPostpost=newHttpPost(URL);post.setHeader("Content-Type","application/json");post.addHeader("Authorization","BasicYWRtaW46");Stringresult="";try{StringEntitys=newStringEntity(json.toString(),"utf-8");s.setContentEncoding(newBasicHeader(HTTP.CONTENT_TYPE,"application/json"));post.setEntity(s);//发送请求HttpResponsehttpResponse=client.execute(post);//获取响应输入流InputStreaminStream=httpResponse.getEntity().getContent();BufferedReaderreader=newBufferedReader(newInputStreamReader(inStream,"utf-8"));StringBuilderstrber=newStringBuilder();Stringline=null;while((line=reader.readLine())!=null)strber.append(line+"\n");inStream.close();result=strber.toString();if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK){returnresult;}else{result="";}}catch(Exceptione){System.out.println("请求异常");thrownewRuntimeException(e);}returnresult;} 获取参数结果的 ?12345678910111213141516/***获取json中的值*@paramjson*@paramkey*@return*/publicstaticStringgetJsonValue(Stringjson,Stringkey){Stringvalue="";try{JSONObjectjsonObj=newJSONObject(json);value=jsonObj.getString(key);}catch(Exceptione){value="";}returnvalue;}
以上这篇浅谈Java代码的微信长链转短链接口使用post请求封装Json(实例)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。