httpClient模拟登陆校内某系统

package com.huowolf;

import java.util.ArrayList;
import java.util.List; 

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


public class Demo1 {
	private static CloseableHttpClient httpclient = HttpClients.createDefault();  
	
	public static void main(String[] args) {
		List params = new ArrayList();
		params.add(new BasicNameValuePair("loginName", "2013023024"));
		params.add(new BasicNameValuePair("password", "2013023024"));
		
		String url = "http://172.16.51.37/";
		post(url, params);
	}

	private static void post(String url,List params) {
		String body = null;
		HttpPost httpPost = null;
		CloseableHttpResponse response = null;
		try {
			httpPost = new HttpPost(url);
			httpPost.setEntity(new UrlEncodedFormEntity(params));	//设置参数
			response = httpclient.execute(httpPost); 				//发送请求
			System.out.println(response.getStatusLine());			//打印响应状态
			
			HttpEntity entity = response.getEntity();			 	//获取返回数据
			body = EntityUtils.toString(entity);
			if(entity!=null)
			{
				System.out.println(body);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				httpclient.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		
	}

	
}

你可能感兴趣的:(javaEE)