(Apache)使用HttpClient方式访问HTTP 有更新!

2017-09-05

Apache使用GET方式访问HTTP
得到访问地址 HttpGet(有参数提供参数)
得到网络访问对象HttpClient,进行连接
得到返回值
如果返回值正常,返回得到的数据对象HttpEntity,得到数据流

注意:
GET方式在URL中传递中文参数乱码问题我解决了。
乱码原因:不管客户端采用什么方式给中文字符编码,最终附加到URL中之前,都将在已有的编码基础上再对字符以ISO-8859-1字符集做二次编码然后再附加到URL中。

即所有的非ASCII字符集参数在URL中最终都是ISO-8859-1编码,如果之前已经进行了一次编码,那么这就是在已有编码的基础上二次编码

解码是编码的逆操作,只要在服务器端对客户端进行的编码再进行对应解码即可。过程如下:
1. 在客户端对中文字符串编码,比如使用UTF-8编码
String codeParam = URLEncoder.encode("中文字符串", "UTF-8");
2. 把这个编码好的codeParam作为参数附加到URL地址中;
3. 服务器端getRequestParameter()方法获得该参数(当然这个参数作为URL提交时已经又被ISO-8859-1编码了一次)
4. 对这个参数做解码,首先要按ISO-8859-1解码一次
byte[ ] decodeBytes = codeParam.getBytes("ISO-8859-1");
5. 再按客户端编码模式做二次解码
String decodeParam = new String(decodeBytes, "UTF-8");

此时获得的decodeParam可以正确显示中文字符。
PS:当然客户端也可以不进行一次编码,那就系统默认的中文编码,但是URL提交时,依然会对这个已经编码的字符串再用ISO-8859-1字符集做二次编码,URL中的非ASCII字符集最终都是ISO-8859-1编码的,这个无法更改。

示例代码:

	package com.hht.apache;

	import java.io.BufferedReader;
	import java.io.IOException;
	import java.io.InputStream;
	import java.io.InputStreamReader;

	import org.apache.catalina.util.URLEncoder;
	import org.apache.http.HttpEntity;
	import org.apache.http.HttpResponse;
	import org.apache.http.client.ClientProtocolException;
	import org.apache.http.client.HttpClient;
	import org.apache.http.client.methods.HttpGet;
	import org.apache.http.impl.client.DefaultHttpClient;
	import org.apache.http.util.EntityUtils;

	public class HttpClient01 {

		public static void main(String[] args) {
			// TODO Auto-generated method stub
			//HttpGet登录验证的实现
			String path = "http://192.168.125.102:8080/ApacheTest/LoginServlet?username=何海涛&password=123";
			//获得HttpClient
			HttpClient client = new DefaultHttpClient();
			//获得HttpGet
			HttpGet httpGet = new HttpGet(path);

			try {
				//获得HttpResponse响应
				HttpResponse httpResponse = client.execute(httpGet);
				//获得响应码
				int code = httpResponse.getStatusLine().getStatusCode();

				if(code==200){
					//获得响应实体
					HttpEntity entity = httpResponse.getEntity();
					//获得响应内容
					InputStream inputStream = entity.getContent();
					//利用流进行输出
					BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
					System.out.println(br.readLine());
					//第二种输出方式
					//System.out.println(EntityUtils.toString(entity,"utf-8"));

				}
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		```

Servlet
package com.hht.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		request.setCharacterEncoding("UTF-8");
		//在这个地方进行两次转码来避免中文在get方式中的乱码
		String username = new String(request.getParameter("username").getBytes("iso-8859-1"),"utf-8");
		String psw = request.getParameter("password");

		if (username.equals("何海涛") && psw.equals("123")) {
			out.println("欢迎" + username + "登陆");

		} else {
			out.println("登陆失败,请检查用户名或者密码是否输入正确....");

		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		request.setCharacterEncoding("UTF-8");
		String username = request.getParameter("username");
		String psw = request.getParameter("password");

		if (username.equals("何海涛") && psw.equals("123")) {
			out.println("欢迎" + username + "登陆");

		} else {
			out.println("登陆失败,请检查用户名或者密码是否输入正确....");

		}
	}

}


下载网络资源的写法
package com.hht.apache;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import org.apache.catalina.util.URLEncoder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class HttpClient01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//HttpGet下载百度logo的实现
		String path = "http://www.baidu.com/img/bdlogo.gif";
		//获得HttpClient
		HttpClient client = new DefaultHttpClient();
		//获得HttpGet
		HttpGet httpGet = new HttpGet(path);

		try {
			//获得HttpResponse响应
			HttpResponse httpResponse = client.execute(httpGet);
			//获得响应码
			int code = httpResponse.getStatusLine().getStatusCode();

			if(code==200){
				//获得响应实体
				HttpEntity entity = httpResponse.getEntity();
//				//获得响应内容
//				InputStream inputStream = entity.getContent();
//				//利用流进行输出
//				BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
//				System.out.println(br.readLine());
				//System.out.println(EntityUtils.toString(entity,"utf-8"));
				//下载网络图片,很简单吧.....
				FileOutputStream outputStream = new FileOutputStream("c:/baidu.gif");
				outputStream.write(EntityUtils.toByteArray(entity));
				outputStream.flush();
				outputStream.close();
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
```

此例接口回调的实现
工具类:

	package com.hht.apachetils;

	import java.io.FileOutputStream;
	import java.io.IOException;

	import org.apache.http.HttpEntity;
	import org.apache.http.HttpResponse;
	import org.apache.http.client.ClientProtocolException;
	import org.apache.http.client.HttpClient;
	import org.apache.http.client.methods.HttpGet;
	import org.apache.http.impl.client.DefaultHttpClient;
	import org.apache.http.util.EntityUtils;

	public class HttPUtils {
		public static void saveImage(String path,SaveImage image){
			//获得HttpClient
					HttpClient client = new DefaultHttpClient();
					//获得HttpGet
					HttpGet httpGet = new HttpGet(path);

					try {
						//获得HttpResponse响应
						HttpResponse httpResponse = client.execute(httpGet);
						//获得响应码
						int code = httpResponse.getStatusLine().getStatusCode();

						if(code==200){
							//获得响应实体
							 HttpEntity entity = httpResponse.getEntity();
							 image.downLoad(entity);
						}
					} catch (ClientProtocolException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
		}

	}
	```

接口
package com.hht.apachetils;

import org.apache.http.HttpEntity;

public interface SaveImage {
	public void downLoad(HttpEntity entity);

}

主线程类的具体实现
package com.hht.apache;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.util.EntityUtils;
import java.io.File;

import com.qianfeng.apachetils.HttPUtils;
import com.qianfeng.apachetils.SaveImage;

public class HttpClient01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//HttpGet下载百度logo的实现
		String path = "http://www.baidu.com/img/bdlogo.gif";
		HttPUtils.saveImage(path,new SaveImage() {

			@Override
			public void downLoad(HttpEntity entity) {
				// TODO Auto-generated method stub
				FileOutputStream outputStream = null;
				File file  = new java.io.File("c:/baidu.gif");
				int  i = 1;
				while(file.exists()){
					file = new File("c:/baidu("+i+").gif");
					i++;
				}
				try {
					outputStream = new FileOutputStream(file);
					outputStream.write(EntityUtils.toByteArray(entity));
					outputStream.flush();
					outputStream.close();
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		});

	}

}
```

Apache使用POST方式访问HTTP
得到访问地址 HttpPost
使用HttpPost写入参数
得到网络访问对象HttpClient,进行连接
得到返回值
如果返回值正常,返回得到的数据对象HttpEntity,得到数据流

代码示例:

	package com.hht.apache;

	import java.io.IOException;
	import java.io.UnsupportedEncodingException;
	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.HttpClient;
	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.util.EntityUtils;

	public class HttpClient02 {
		public static void main(String[] args) throws UnsupportedEncodingException {
			// TODO Auto-generated method stub
			// HttpPost登录验证的实现
			String path = "http://192.168.125.102:8080/ApacheTest/LoginServlet";
			// 获得HttpClient
			HttpClient client = new DefaultHttpClient();
			// 获得HttpPost
			HttpPost httpPost = new HttpPost(path);

			// 产生参数对

			NameValuePair pair = new BasicNameValuePair("username", "hht");

			NameValuePair pair2 = new BasicNameValuePair("password", "123");

			List nameValuePairs = new ArrayList();
			nameValuePairs.add(pair2);
			nameValuePairs.add(pair);

			try {
				HttpEntity httpEntity = new UrlEncodedFormEntity(nameValuePairs);
				httpPost.setEntity(httpEntity);
			} catch (UnsupportedEncodingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

			try {
				// 获得HttpResponse响应
				HttpResponse httpResponse = client.execute(httpPost);
				// 获得响应码
				int code = httpResponse.getStatusLine().getStatusCode();

				if (code == 200) {
					// 获得响应实体
					HttpEntity entity = httpResponse.getEntity();
					// //获得响应内容
					// InputStream inputStream = entity.getContent();
					// //利用流进行输出
					// BufferedReader br = new BufferedReader(new
					// InputStreamReader(inputStream));
					// System.out.println(br.readLine());
					// 第二种输出方式
					System.out.println(EntityUtils.toString(entity, "utf-8"));

				}
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

Servlet类:

	package com.hht.servlet;

	import java.io.IOException;
	import java.io.PrintWriter;

	import javax.servlet.ServletException;
	import javax.servlet.http.HttpServlet;
	import javax.servlet.http.HttpServletRequest;
	import javax.servlet.http.HttpServletResponse;

	/**
	 * Servlet implementation class LoginServlet
	 */
	public class LoginServlet extends HttpServlet {
		private static final long serialVersionUID = 1L;

		/**
		 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
		 */
		protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			// TODO Auto-generated method stub

			response.setCharacterEncoding("UTF-8");
			PrintWriter out = response.getWriter();
			request.setCharacterEncoding("UTF-8");
			//在这个地方进行两次转码来避免中文在get方式中的乱码
			String username = new String(request.getParameter("username").getBytes("iso-8859-1"),"utf-8");
			String psw = request.getParameter("password");

			if (username.equals("hht") && psw.equals("123")) {
				out.println("欢迎" + username + "登陆");

			} else {
				out.println("登陆失败,请检查用户名或者密码是否输入正确....");

			}
		}

		/**
		 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
		 */
		protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			// TODO Auto-generated method stub

			response.setCharacterEncoding("UTF-8");
			PrintWriter out = response.getWriter();
			request.setCharacterEncoding("UTF-8");
			String username = request.getParameter("username");
			String psw = request.getParameter("password");
			 System.out.println(username+" "+psw);
			if (username.equals("hht") && psw.equals("123")) {
				out.println("欢迎" + username + "登陆");

			} else {
				out.println("登陆失败,请检查用户名或者密码是否输入正确....");

			}
		}

	}
	```
评论
发表评论