使用java构建客户端访问秀代码Rest Web Service

本文来自hi.baidu.com/yingnet,版权所有,转载请注明出处,谢谢合作
昨天使用了秀代码(www.xiudaima)的firefox插件,感觉效果挺了。又看到网站提供Rest服务,便想着构建一个客户端,由于返回的是JSON数据,所以需要JSON解析器,在www.json.org上看到了google-gson,项目地址http://code.google.com/p/google-gson/,于是下载来用用,由于Google产品向来易用,因此看了下API,很快就用上了,下面是简单的代码

package coderestclient;import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
/** * * @author hitdong */
public class Main{    
/**     * @param args the command line arguments     */    
	public static void main(String[] args) throws Exception    {        
		URL url = new URL("http://www.xiudaima.com/rest/v1/postcode");        
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();        
		conn.setDoOutput(true);        
		PrintWriter pw = new PrintWriter(conn.getOutputStream());        
		String userName = "user@xiudaima.com";//注册秀代码是的邮箱        
		String password = "password";//秀代码给的密码        
		String code = "printf(\"Hello world!\n\")";        
		pw.println("title=c&username=" + userName +                
			"&password=" + password + "&lang=c&" +               
 			"description=" + code);        
		pw.close();        
		Reader rd = new InputStreamReader(conn.getInputStream());        
		JsonElement jsonElement = new JsonParser().parse(rd);        
		rd.close();        
		JsonObject jsonObject = jsonElement.getAsJsonObject();        
		System.out.println(jsonObject.get("highlightcode").getAsString());    
}}

得到如下的输出
<div class="highlight_div"><table class="highlighttable"><tr><td class="linenos"><pre>1
2</pre></td><td class="code"><div class="highlight"><pre>printf(<span style="color: #BA2121">&quot;Hello world!</span>
<span style="color: #BA2121">&quot;)</span>
</pre></div>
</td></tr></table></div>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值