Java 实现快递查询 (免费) ,不用输入验证码

查快递的时候发现了一个http://www.kaidi100.com 是金蝶旗下的下个网站,做得很不错,几乎可以查所以的快递公司的,该站提供了API查询快递,API需要申请key.申请Key需要做它网站链接。无奈,哥的网站早到期,没续费了,于是trace了一把请求,直接用Java httpurlconnection 搞起,只是给个例子,可以再接着封装。中间遇到过乱码问题,最后发现是内容进行了gzip压缩,trace时候没有仔细看response header ,吃了回亏 教训。

 

package com.hailsoft.test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.zip.GZIPInputStream;


/**
 * @author admin
 *
 */
public class App {
	public static void main(String[] args) {
		String url = "http://www.kuaidi100.com/query?type=shentong&postid=请更换为你的申通运单号&id=1&valicode=&temp=0.3015635129995644";
		
		try {
			HttpURLConnection.setFollowRedirects(true);
			HttpURLConnection http = (HttpURLConnection) (new URL(url).openConnection());
			http.setDoOutput(true);
			http.setDoOutput(true);
			http.setInstanceFollowRedirects(true);
			http.setRequestMethod("GET");
			http.setRequestProperty("Connection", "keep-alive");
			http.setRequestProperty("X-Requested-With", "XMLHttpRequest");
			http.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.92 Safari/537.1 LBBROWSER");
			http.setRequestProperty("Accept", "*/*");
			http.setRequestProperty("Referer", "http://www.kuaidi100.com/");
			http.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
			http.setRequestProperty("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
			http.setRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
			
			System.out.println("response  is : "+http.getResponseCode()+" "+http.getResponseMessage());
			String contentEncoding = http.getContentEncoding();
			System.out.println("response  encoding is : "+contentEncoding);
			InputStream  in = null;
			if("gzip".equalsIgnoreCase(contentEncoding)){
				in = new GZIPInputStream(http.getInputStream()); 
			}else{
				in = http.getInputStream();
			}
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			int data = -1;
			while((data = in.read())!=-1){
				baos.write(data);
			}
			String resp = baos.toString("utf8");
			System.out.println(resp);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}

 

 

你可能感兴趣的:(Java)