httpclient发送Json格式数据举例之google短网址
程序员文章站
2022-07-13 11:36:54
...
public String getGooGlShortUrl(String apiKey,String sourceUrl) throws Exception{ String shortUrl = null; DefaultHttpClient httpClient = new DefaultHttpClient(); try { HttpPost request = new HttpPost(WeiboConfig.getValue("google.shortUrl")); Map<String,String> map = new HashMap<String, String>(); map.put("longUrl", sourceUrl); map.put("key", WeiboConfig.getValue("google.apiKey")); String jsonString = JsonUtil.getJsonString4JavaPOJO(map); StringEntity params =new StringEntity(jsonString,"UTF-8"); request.addHeader("content-type", "application/json"); request.setEntity(params); HttpResponse response = httpClient.execute(request); HttpEntity entity = response.getEntity(); InputStream instream = entity.getContent(); BufferedReader in = new BufferedReader(new InputStreamReader(instream,"UTF-8")); StringBuffer sb = new StringBuffer(); String data = null; while((data = in.readLine())!=null){ sb.append(data); sb.append("\n"); } if(in != null) in.close(); if(StringUtils.isNotBlank(sb.toString())){ Object id = JsonUtil.getMap4Json(sb.toString()).get("id"); shortUrl = id==null?null:id.toString(); } }catch (Exception e) { } finally { httpClient.getConnectionManager().shutdown(); return shortUrl; } }
需要用到的httpclient的jar包在附件中。