`
jsczxy2
  • 浏览: 1255262 次
  • 性别: Icon_minigender_1
  • 来自: 常州
文章分类
社区版块
存档分类
最新评论

httpclient发送Json格式数据举例之google短网址

阅读更多

 

	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包在附件中。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics