如何在Java项目中利用post请求对JSON进行封装?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。直接上代码String longUrl = 
如何在Java项目中利用post请求对JSON进行封装?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
直接上代码
String longUrl = "https://open.weixin.qq.com/connect/oauth3/authorize?appid=" + MpUtil.APPID + "&redirect_uri=" + MpUtil.HOMEPAGE + "/nweixinLoginPc.fo%3Frandomcode=" + randomcode + "&response_type=code&scope=snsapi_userinfo&state=account#wechat_redirect";//什么不重要 ,自己的长链 String accessToken = MpUtil.getAccessToken(MpUtil.APPID, MpUtil.APPSECRET); String shortUrl = null;//短连接地址,生成二维码用,识别快 String HttpUrl = "https://api.weixin.qq.com/cgi-bin/shorturl?access_token="+accessToken; //此处访问微信短链方法 jsONObject jsonObject = new JSONObject(); jsonObject.put("action", "long2short"); jsonObject.put("long_url", longUrl); String transJson = jsonObject.toString()+httpUrl; RequestEntity se = new StringRequestEntity(transJson, "application/json", "UTF-8"); //微信返回的字符串 //成功 {"errcode":0,"errmsg":"ok","short_url":"http:\/\/w.url.cn\/s\/AvCo6Ih"} //失败 {"errcode":40013,"errmsg":"invalid appid"} String resultsString = post(jsonObject,httpUrl); //封装的post方法 String shortUrl = MpUtil.getJsonValue(resultsString, "short_url");//得到的短链 ?12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849public static String post(JSONObject json,String URL) { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(URL); post.setHeader("Content-Type", "application/json"); post.addHeader("Authorization", "Basic YWRtaW46"); String result = ""; try { StringEntity s = new StringEntity(json.toString(), "utf-8"); s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); post.setEntity(s); // 发送请求 HttpResponse httpResponse = client.execute(post); // 获取响应输入流 InputStream inStream = httpResponse.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader( inStream, "utf-8")); StringBuilder strber = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) strber.append(line + "\n"); inStream.close(); result = strber.toString(); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { return result; } else { result=""; } } catch (Exception e) { System.out.println("请求异常"); throw new RuntimeException(e); } return result; } 获取参数 结果的 ?12345678910111213141516 public static String getJsonValue(String json, String key) { String value = ""; try { JSONObject jsonObj = new JSONObject(json); value = jsonObj.getString(key); } catch (Exception e) { value = ""; } return value; }
关于如何在Java项目中利用post请求对Json进行封装问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注编程网精选频道了解更多相关知识。
--结束END--
本文标题: 如何在Java项目中利用post请求对Json进行封装
本文链接: https://www.lsjlt.com/news/224710.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-14
2024-05-14
2024-05-14
2024-05-14
2024-05-14
2024-05-14
2024-05-14
2024-05-14
2024-05-14
2024-05-14
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0