本文来自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">"Hello world!</span>
<span style="color: #BA2121">")</span>
</pre></div>
</td></tr></table></div>