
有句名言,叫做10000小时成为某一个领域的专家。姑且不辩论这句话是否正确,让我们到达10000小时的时候再回头来看吧。
本文作者Java 现经验约为21 Hour,请各位不吝赐教。
继续心情不佳,那就来获得一个天气的程序吧。
目标
因本人目前在杭州,就先显示一个杭州的天气情况吧。
项目类型就暂定为控制台程序吧,以后再改造。
就用那个众所周知的天气接口吧:
http://m.weather.com.cn/data/101210101.html
过程
随手搜索下java http 就出来了我们想要的例子。
https://hc.apache.org/httpclient-3.x/preference-api.html
api 的用法纠结了半天,java jar包版本实在是个大坑呢。好在最后发现一般在哪里下jar 包,哪里就会有api 的说明,这个就是开源的利弊了吧。
然后是耳熟能详的乱码问题了。
代码
package hello; import java.io.IOException; import java.io.InputStream; import java.util.Scanner; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; public class Weather { private static final String CONTENT_CHARSET = "utf-8"; public static void main(String[] args) throws ClientProtocolException, IOException { // http://m.weather.com.cn/data/101210101.html HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter("http.protocol.content-charset", CONTENT_CHARSET); HttpGet httpgets = new HttpGet("http://m.weather.com.cn/data/101210101.html"); HttpResponse response = httpclient.execute(httpgets); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instreams = entity.getContent(); String str = convertStreamToString(instreams); System.out.println(str); httpgets.abort(); } } public static String convertStreamToString(InputStream is) { StringBuilder sb = new StringBuilder(); Scanner in = new Scanner(is, "UTF-8"); while (in.hasNextLine()) { sb.append(in.nextLine()); } in.close(); return sb.toString(); } }
问题
1 Stream 转 string 的 N种方式的优缺点
2 Stream 转 string 某些方式容易出现乱码
3 可以参照这里
http://unmi.cc/java-convert-inputstream-to-string
4 Steam 操作的一些基本类库的了解