Httpclient-My坑

版权声明:柠檬乐园:200145783 https://blog.csdn.net/u014431237/article/details/80580091

学习了一下Httpclient,用SmartQQ练下手

坑一:Referer

HTTP Referer是header的一部分,当浏览器向web服务器发送请求的时候,一般会带上Referer,告诉服务器我是从哪个页面链接过来的,服务器基此可以获得一些信息用于处理。

不管三七二十一 :headers.put("Referer", url);  没错

坑二:Post参数装填

参数为 name={json} 的样子  反斜杠也要转义  转义 转义!!!

 直接编码传递参数  请求头 headers.put("Content-type", "application/x-www-form-urlencoded");即可

参数  和 头的 封装:

        /**
	 * 参数
	 * 
	 * @param parameterMap
	 * @return
	 */
	private static  List<NameValuePair> getParam(Map<String, Object> parameterMap) {
		List<NameValuePair> param = new ArrayList<NameValuePair>();
		for (Map.Entry<String, Object> entry : parameterMap.entrySet()) {
		    param.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
		}
		return param;
	}

	/**
	 * @param httpRequest
	 *            post 和 get 都可以 最终都是继承HttpRequestBase
	 * @param headerMap
	 *            自己封装的请求头 cookie可以直接放到头中
	 */
	private static void addHeaders(HttpRequestBase httpRequest, Map<String, String> headerMap) {
		for (Map.Entry<String, String> entry : headerMap.entrySet()) {
			httpRequest.addHeader(entry.getKey(), entry.getValue());
		}
	}

Get请求获取二维码图片字节流

	/**
	 * @param url
	 * @param headers
	 *            提交cookie 请自行封装其中
	 * @param setCookie
	 *            返回的cookie
	 * @return 图片的字节流
	 */
	public static byte[] sendGet(String url, Map<String, String> headers, StringBuilder setCookie) {

		// 返回值
		byte[] httpbyte = null;

		// 设置HTTP请求参数
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000) // 设置连接超时时间
				.setConnectionRequestTimeout(5000) // 设置请求超时时间
				.setSocketTimeout(5000).build();

		CloseableHttpClient client = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet(url);
		// 调用 自定义的头添加函数
		addHeaders(httpGet, headers);

		httpGet.setConfig(requestConfig);

		try {
			// 执行请求
			CloseableHttpResponse chresponse = client.execute(httpGet);

			// 取响应的结果
			int statusCode = chresponse.getStatusLine().getStatusCode();
			if (statusCode == 200) {

				// 把返回的cookie 全部添加到setcookie中
				Header[] rehead = chresponse.getHeaders("set-cookie");
				for (Header header : rehead) {
					setCookie.append(header.getValue());
					System.out.println(header.getValue());
				}
				// 获取图片的字节流
				httpbyte = EntityUtils.toByteArray(chresponse.getEntity());

			} else if (statusCode == 400) {
				System.out.println("400....");
			} else if (statusCode == 500) {
				System.out.println("500.......");
			}

		} catch (ClientProtocolException e) {
			System.out.println("http接口调用异常:ClientProtocolException  url is::" + url + e);
			return null;
		} catch (Exception e) {
			System.out.println("http接口调用异常: Exception  url is::" + url + e);
			return null;
		} finally {

			try {
				client.close();
			} catch (IOException e) {
				System.out.println("http接口调用异常:IOException url is::" + url + e);
			}
		}
		return httpbyte;
	}

Get请求获取内容

        /**
	 * @param url
	 * @param headers
	 *            提交cookie 请自行封装其中
	 * @param redirects
	 *            是否重定向
	 * @param setCookie
	 *            返回的cookie
	 * @return 返回字符串
	 */
	public static String sendGet(String url, Map<String, String> headers, boolean redirects, StringBuilder setCookie) {

		// 返回值
		String result = null;

		// 设置HTTP请求参数
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000) // 设置连接超时时间
				.setConnectionRequestTimeout(5000) // 设置请求超时时间
				.setSocketTimeout(5000).setCookieSpec(CookieSpecs.STANDARD).setRedirectsEnabled(redirects) // 是否允许自动重定向
				.build();

		CloseableHttpClient client = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet(url);
		// 调用头添加函数
		addHeaders(httpGet, headers);

		httpGet.setConfig(requestConfig);

		try {
			// 执行请求
			CloseableHttpResponse chresponse = client.execute(httpGet);

			// 取响应的结果
			int statusCode = chresponse.getStatusLine().getStatusCode();
			// System.out.println("响应头"+statusCode);
			if (statusCode == 200) {

				// 把返回的cookie 全部添加到setcookie中
				Header[] rehead = chresponse.getHeaders("Set-Cookie");
				for (Header header : rehead) {
					StringBuilder sb = new StringBuilder(header.getValue());
					String ck = sb.substring(0, sb.indexOf(";")) + ";";
					System.out.println(ck);
					setCookie.append(ck);
				}
				result = EntityUtils.toString(chresponse.getEntity(), "UTF-8");

				System.out.println("这是返回结果" + result);

			} else if (statusCode == 400) {
				System.out.println("400....");
			} else if (statusCode == 500) {
				System.out.println("500.......");
			}

		} catch (ClientProtocolException e) {
			System.out.println("http接口调用异常:ClientProtocolException  url is::" + url + e);
			return null;
		} catch (Exception e) {
			System.out.println("http接口调用异常: Exception  url is::" + url + e);
			return null;
		} finally {

			try {
				client.close();
			} catch (IOException e) {
				System.out.println("http接口调用异常:IOException url is::" + url + e);
			}
		}
		return result;
	}

Post请求:map方式提交参数 

	/**
	 * @param url
	 * @param params   参数
	 * @param headers  请求头  cookie 直接封装其中
	 * @param redirects  是否重定向
	 * @param setCookie  返回的cookie  可以为null
	 * @return 内容
	 */
	public static String sendPost(String url, Map<String, Object> params, Map<String, String> headers,
			boolean redirects, StringBuilder setCookie) {
		// 返回值
		String result = null;

		// 设置HTTP请求参数
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000) // 设置连接超时时间
				.setConnectionRequestTimeout(5000) // 设置请求超时时间
				.setSocketTimeout(5000).setCookieSpec(CookieSpecs.STANDARD).setRedirectsEnabled(redirects) // 是否允许自动重定向
				.build();

		CloseableHttpClient client = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		// 调用头添加函数
		addHeaders(httpPost, headers);

		// 装填参数 调用自定义的函数
		List<NameValuePair> nvps = getParam(params);
		try {
			//需要url 编码  少年
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
			// 装填请求头
			httpPost.setConfig(requestConfig);
			// 执行请求
			CloseableHttpResponse chresponse = client.execute(httpPost);

			// 取响应的结果
			int statusCode = chresponse.getStatusLine().getStatusCode();
			// System.out.println("响应头"+statusCode);
			if (statusCode == 200) {

				// 把返回的cookie 全部添加到setcookie中   不需要可以注释  无所谓
				// Header[] rehead = chresponse.getHeaders("Set-Cookie");
				// for (Header header : rehead) {
				// StringBuilder sb = new StringBuilder(header.getValue());
				// String ck = sb.substring(0,sb.indexOf(";"))+";";
				// System.out.println(ck);
				// setCookie.append(ck);
				// // System.out.println(header.getValue());
				// }
				result = EntityUtils.toString(chresponse.getEntity(), "UTF-8");

				System.out.println("Post结果" + result);
			} else if (statusCode == 400) {
				System.out.println("400....");
			} else if (statusCode == 500) {
				System.out.println("500.......");
			}

		} catch (ClientProtocolException e) {
			System.out.println("http接口调用异常:ClientProtocolException  url is::" + url + e);
			return null;
		} catch (Exception e) {
			System.out.println("http接口调用异常: Exception  url is::" + url + e);
			return null;
		} finally {
			try {
				client.close();
			} catch (IOException e) {
				System.out.println("http接口调用异常:IOException url is::" + url + e);
			}
		}
		return result;
	}

Post请求:直接编码方式提交参数 (如:name=lemon&pasword=123456) 

	/**
	 * 
	 * @param url
	 * @param headers
	 *            提交cookie 请自行封装其中
	 * @param redirects
	 *            是否重定向
	 * @param setCookie
	 *            返回的cookie
	 * @return
	 */
	public static String sendPost(String url, String params, Map<String, String> headers, boolean redirects,
			StringBuilder setCookie) {
		// 返回值
		String result = null;

		// 设置HTTP请求参数
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000) // 设置连接超时时间
				.setConnectionRequestTimeout(5000) // 设置请求超时时间
				.setSocketTimeout(5000).setCookieSpec(CookieSpecs.STANDARD).setRedirectsEnabled(redirects) // 是否允许自动重定向
				.build();

		CloseableHttpClient client = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		// 调用头添加函数
		addHeaders(httpPost, headers);

		try {
			// 装填请求头
			httpPost.setConfig(requestConfig);

			StringEntity entity = new StringEntity(params, Consts.UTF_8);
			httpPost.setEntity(entity);

			// 执行请求
			CloseableHttpResponse chresponse = client.execute(httpPost);

			// 取响应的结果
			int statusCode = chresponse.getStatusLine().getStatusCode();
			System.out.println("响应头" + statusCode);
			if (statusCode == 200) {

				// 把返回的cookie 全部添加到setcookie中   不需要可以注释  无所谓
				// Header[] rehead = chresponse.getHeaders("Set-Cookie");
				// for (Header header : rehead) {
				// StringBuilder sb = new StringBuilder(header.getValue());
				// String ck = sb.substring(0,sb.indexOf(";"))+";";
				// System.out.println(ck);
				// setCookie.append(ck);
				// // System.out.println(header.getValue());
				// }
				result = EntityUtils.toString(chresponse.getEntity(), "UTF-8");
				System.out.println("Post结果" + result);

			} else if (statusCode == 400) {
				System.out.println("400....");
			} else if (statusCode == 500) {
				System.out.println("500.......");
			}

		} catch (ClientProtocolException e) {
			System.out.println("http接口调用异常:ClientProtocolException  url is::" + url + e);
			return null;
		} catch (Exception e) {
			System.out.println("http接口调用异常: Exception  url is::" + url + e);
			return null;
		} finally {

			try {
				client.close();
			} catch (IOException e) {
				System.out.println("http接口调用异常:IOException url is::" + url + e);
			}
		}
		return result;
	}

Java调用执行JavaScript

package com.lemo.js;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

/**
 * @author AnxiangLemon
 *  java调用直接调用js函数
 */
public class JsUtils {

	public static Integer getqrToken(String qrsig) {
		ScriptEngineManager manager = new ScriptEngineManager();
		ScriptEngine engine = manager.getEngineByName("javascript");
		String jsfun = "function  hash33(t) {" + "for (var e = 0, i = 0, n = t.length; n > i; ++i){"
				+ "e += (e << 5) + t.charCodeAt (i);}" + "return 2147483647& e;	};";
		
		Integer scriptResult = 0;
		try {
			engine.eval(jsfun);
			Invocable invocable = (Invocable) engine;
			scriptResult = (Integer) invocable.invokeFunction("hash33", qrsig);
			System.out.println(scriptResult);
		} catch (ScriptException e) {
			System.out.println("Error executing script: " + e.getMessage() + " script:[" + jsfun + "]");
		} catch (NoSuchMethodException e) {
			System.out.println("Error executing script,未找到需要的方法: " + e.getMessage() + " script:[" + jsfun + "]");
			e.printStackTrace();
		}
		return scriptResult;
	}

}

猜你喜欢

转载自blog.csdn.net/u014431237/article/details/80580091
my