java 通过HTTPclient进行通信

package org.zzw.xxcj;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicResponseHandler;
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 TestTx {

	public static void main(String[] args) throws ClientProtocolException, IOException {
		
		//默认的http客户端,用来执行请求
		DefaultHttpClient client = new DefaultHttpClient();
		
		//两个访问的不同方式
		HttpPost httpPost = null;
		HttpGet httpGet = null;
		
		//服务器返回的响应
		HttpResponse response = null;
		
		//这是响应的控制者,控制响应的返回值,这里是string
		ResponseHandler<String> handler = new BasicResponseHandler();
		
		//先登录
		String http1 = "http://localhost:8081/sawp/logintemp.jsp?loginname=ck&password=123456";
		
		httpGet = new HttpGet(http1);
		
		//打开连接
		response = client.execute(httpGet);

        //返回这次连接的状态码
		//System.out.println(response.getStatusLine());
		
		//接收返回的实体
		HttpEntity entity = response.getEntity();
		
        //每次做完连接都要写这个,这个就是关闭连接,避免下面的请求出现问题
		if(entity!=null){
			entity.consumeContent();
		}
		
		//得到这次连接所产生的cookie,可能是多个
		List<Cookie> cookie = client.getCookieStore().getCookies();
		
		if(cookie.isEmpty()){
			System.out.println("None");
		}else{
			for (int i = 0; i < cookie.size(); i++) {
				System.out.println("-"+cookie.get(i).toString());
			}
		}
		
		httpPost = new HttpPost(http1);
		
		//这个集合是存放参数的
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		
		//存放参数示例:new BasicNameValuePair("键","值"),效果相当于   http://localhost:8081/sawp/logintemp.jsp?loginname=ck&password=123456
//		nvps.add(new BasicNameValuePair("loginname", "ck"));
//		nvps.add(new BasicNameValuePair("password", "123456"));
		
		//将参数实体放到请求中,这里还把参数换成utf-8格式
		httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

		//打开请求返回相应
		response = client.execute(httpPost);
		
		//得到响应的实体
		entity = response.getEntity();
		
		if(entity!=null){
			entity.consumeContent();
		}
		
		System.out.println("------------------------------------------------------");
		
		//将要请求的地址
		http1 = "http://localhost:8081/sawp/rylist/ry_list.jsp";
		
		//创建一个连接,这里是get方式
		httpGet = new HttpGet(http1);
		
		//客户端发送请求,并传入控制者,才可以返回string格式的结果
		String res = client.execute(httpGet,handler);
		
		System.out.println(res);
	}
}

猜你喜欢

转载自blog.csdn.net/rjkkaikai/article/details/81480618