`

httpClient入门

    博客分类:
  • Jave
阅读更多
package filter.test;

import java.io.IOException;
import java.io.StringReader;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
/**
 * @author llg 2011-03-31
 */
public class HttpTest {
	public static void main(String[] args) throws HttpException, IOException,
			DocumentException {
//以下是这段代码是查询手机号码归属地及卡的类型
		String url = "http://www.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo?mobileCode=13488056243&userID=";
		HttpClient http = new HttpClient();
		// 使用POST方法
		// HttpMethod method = new PostMethod("http://java.sun.com";);
		// 使用GET方法
		HttpMethod method = new GetMethod(url);

		http.executeMethod(method);
		// 打印服务器返回的状态
		System.out.println(method.getStatusLine());
		String xml = method.getResponseBodyAsString();
		// 将返回的字符串转成XML 然后用dom4j解析
		Document doc = null;
		SAXReader sax = new SAXReader();
		doc = sax.read(new StringReader(xml));
		System.out.println(doc.getRootElement().getText());
		// 释放连接
		method.releaseConnection();
//		method2();

	}

	static void method2() throws IOException {
		HttpClient client = new HttpClient();
		client.getHostConfiguration().setHost("www.imobile.com.cn", 80, "http");
		HttpMethod method = getPostMethod();// 使用POST方式提交数据
		client.executeMethod(method);
		// 打印服务器返回的状态
		System.out.println(method.getStatusLine());
		// 打印结果页面
		String response = new String(method.getResponseBodyAsString().getBytes(
				"8859_1"));
		// 打印返回的信息
		System.out.println(response);
		method.releaseConnection();
	}

	// get
	static HttpMethod getGetMethod() {
		return new GetMethod("/simcard.php?simcard=13488056243");
	}

	// post
	static HttpMethod getPostMethod() {
		PostMethod post = new PostMethod("/simcard.php");
		NameValuePair simcard = new NameValuePair("simcard", "13488056243");
		post.setRequestBody(new NameValuePair[] { simcard });
		return post;
	}
}

 



资料推荐:http://www.blogjava.net/Alpha/archive/2007/01/22/95216.html
  • jar.rar (636.3 KB)
  • 下载次数: 34
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics