Java httpclient

Java httpclient

commons-codec-1.4.jar
commons-logging-1.1.1.jar
httpclient-4.1.2.jar
httpclient-cache-4.1.2.jar
httpcore-4.1.2.jar
httpmime-4.1.2.jar

import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class ClientFormLogin {

    public static void main(String[] args) throws Exception {

    	// 创建httpclient
        DefaultHttpClient httpclient = new DefaultHttpClient();
        try {

        	// 创建httpost
            HttpPost httpost = new HttpPost("http://192.168.0.13:7001/defaultroot/LogonAction.do");

            // 创建参数
            List <NameValuePair> nvps = new ArrayList <NameValuePair>();
            nvps.add(new BasicNameValuePair("localeCode", "zh_cn"));
            nvps.add(new BasicNameValuePair("userName", "jzh"));
            nvps.add(new BasicNameValuePair("userPassword", "1"));

            httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

            // 执行post请求
            HttpResponse response = httpclient.execute(httpost);
            // 获取响应实体
            HttpEntity entity = response.getEntity();
            
            // 获取响应状态
            int statuscode = response.getStatusLine().getStatusCode();
            
            // 如果请求成功
            if (statuscode == HttpStatus.SC_OK) {
                if (entity != null) {
                	// 输出返回内容。
                	System.out.println(EntityUtils.toString(entity));	
                }
            }

            EntityUtils.consume(entity);

        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    }
}

 

发表回复

您的电子邮箱地址不会被公开。