httpClient 使用post方式访问获取数据例子

httpClient使用post方式获取数据

用的的jar包从这里下载:

 
下面说一下httpClient使用post方式访问获取数据例子:
import java.io.IOException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

//HttpClient使用get的方式
public class HttpClientByPost {
	Log log = LogFactory.getLog( HttpClientByPost.class );

	public static void main( String[] args ) throws IOException {
		HttpClient client = new HttpClient();
		// 设置代理服务器地址和端口
		// client.getHostConfiguration().setProxy( "172.26.184.189", 80 );
		//设置请求的url ,端口号,http或https
		client.getHostConfiguration().setHost( "www.jsjtt.com", 80, "http" );
		//
		PostMethod method = new PostMethod( "/e/action/ShowInfo.php" );
		NameValuePair simcard = new NameValuePair( "classid", "22" );
		NameValuePair simcard2 = new NameValuePair( "id", "14" );
		method.setRequestBody( new NameValuePair[] { simcard,simcard2 } );
		
//		method.setParameter( "classid", "22" );
//		method.setParameter( "id", "14" );
		// 这里设置字符编码,避免乱码
		method.setRequestHeader( "Content-Type", "text/html;charset=utf-8" );
		
		client.executeMethod( method );
		// 打印服务器返回的状态
	
		System.out.println( method.getStatusLine() );

		// 获取返回的html页面
		byte[] body = method.getResponseBody();
		// 打印返回的信息
		System.out.println( new String( body, "utf-8" ) );
		// 释放连接
		method.releaseConnection();
	}

}

 

 

 

来源://作者:/更新时间:2012-12-20
相关文章
评论:
验证码:
匿名评论: