Solo  当前访客:4 登录 注册

喧哗博客-http://blog.xuahua.com

繁华过后的沉寂--技术经验分享
浏览次数: 94,390    文章总数: 91    评论总数: 3
标签:

微信接口开发系列之九群发消息上传图片 有更新!

微信接口定义如下

上传图文消息内的图片获取URL【订阅号与服务号认证后均可用】

请注意,本接口所上传的图片不占用公众号的素材库中图片数量的5000个的限制。图片仅支持jpg/png格式,大小必须在1MB以下。

接口调用请求说明

http请求方式: POST
https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN
事后证明,上传图片的接口请使用 http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=image 调用示例(使用curl命令,用FORM表单方式上传一个图片): curl -F media=@test.jpg "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN"

参数说明

参数是否必须说明
access_token 调用接口凭证
media form-data中媒体文件标识,有filename、filelength、content-type等信息

返回说明 正常情况下的返回结果为:

{
    "url":  "http://mmbiz.qpic.cn/mmbiz/gLO17UPS6FS2xsypf378iaNhWacZ1G1UplZYWEYfwvuU6Ont96b1roYs CNFwaRrSaKTPCUdBK9DgEHicsKwWCBRQ/0"
}

其中url就是上传图片的URL,可用于后续群发中,放置到图文消息中。

错误时微信会返回错误码等信息,请根据错误码查询错误信息。

 

 

使用httpclient 上传图片代码如下:

/**
	 * 微信客服消息,上传文件接口使用
	 * @param url  微信提供的上传地址
	 * @param file 上传图片地址,此处必须是本地文件路径
	 * @param filename 对应的上传文件名
	 * @return
	 */
	public static String postfile(String url,String file,String filename){
		StringBuilder sb = new StringBuilder();
		CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        HttpPost httppost = new HttpPost(url); 
        postRequestconfig(httppost);
        
        try {
        	HttpEntity entityfile = MultipartEntityBuilder.create()  
        			.addBinaryBody("file", new File(file), ContentType.DEFAULT_BINARY, file).addTextBody("filename",filename)  
        			.build();  
        	httppost.setEntity(entityfile);  
	    	HttpResponse response = httpclient.execute(httppost);
			int statusOk = response.getStatusLine().getStatusCode();
			if(logger.isInfoEnabled()){
		        	logger.info(url+"result-statusCode=>>"+statusOk);
		    }
	        if(statusOk == HttpStatus.SC_OK){
	        	HttpEntity entity = response.getEntity();
	        	BufferedInputStream instream = new BufferedInputStream(entity.getContent()); 
		        byte[] chars = new byte[2048];
		        int len=0;
		        while((len=instream.read(chars))!=-1){
		        	sb.append(new String(chars,0,len));
		        }
	        }else{
	        	logger.error(url+"result->网络异常.."+statusOk);
	        }
	        if(logger.isInfoEnabled()){
	        	logger.info(url+"result->"+sb.toString());
	        }
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	    return sb.toString();
	}

httpclient4.x 模拟post请求

     /**
	 * @param url
	 * @param data
	 * @param encode
	 *            指定头编码
	 * @return
	 */
	public static String postRequest(String url, Map<String, String> data,
			String encode) {
		if(StringUtils.isBlank(encode)){
			encode = "utf8";
		}
		StringBuilder sb = new StringBuilder();
		CloseableHttpClient httpclient = HttpClientBuilder.create().build();
		HttpPost httppost = new HttpPost(url);
		postRequestconfig(httppost);
        try{
        	if (data != null) {
        		List<NameValuePair> dataary = new ArrayList<NameValuePair>();
				for (String mapKey : data.keySet()) {
					// 填入各个表单域的值
					String vString = data.get(mapKey) == null ? "" : data.get(
							mapKey).toString();
					NameValuePair data1 = new BasicNameValuePair(mapKey, vString);
					dataary.add(data1);
				}
				// 将表单的值放入postMethod中
				 httppost.setEntity(new UrlEncodedFormEntity(dataary,encode));
			}
	        CloseableHttpResponse response = httpclient.execute(httppost);
	        int statusOk = response.getStatusLine().getStatusCode();
	        if(logger.isInfoEnabled()){
	        	logger.info(url+"result-statusCode=>>"+statusOk);
	        }
	        if(statusOk == HttpStatus.SC_OK){
	        	HttpEntity entity = response.getEntity();
	        	BufferedInputStream instream = new BufferedInputStream(entity.getContent()); 
		        byte[] chars = new byte[2048];
		        int len=0;
		        while((len=instream.read(chars))!=-1){
		        	sb.append(new String(chars,0,len,encode));
		        }
		        instream.close();
		        response.close();
	        }else{
	        	logger.error(url+"result->网络异常.."+statusOk);
	        }
	        if(logger.isInfoEnabled()){
	        	logger.info(url+"result->"+sb.toString());
	        }
        }catch(Exception e){
        	e.printStackTrace();
        }finally{
        	httppost.releaseConnection();
        	try {
				httpclient.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
        return sb.toString();
	}

httpclient4.x 模拟get请求

private static void postRequestconfig(HttpPost httppost){
		 //配置请求的超时设置
		RequestConfig requestConfig = RequestConfig.custom()
				.setConnectionRequestTimeout(Timeout)
				.setConnectTimeout(Timeout)  
				.setSocketTimeout(Timeout).build();
        httppost.setConfig(requestConfig);
	}
public static String getRequest(String url) { StringBuilder sb = new StringBuilder(); CloseableHttpClient httpclient = HttpClientBuilder.create().build(); HttpGet httpget = new HttpGet(url); getRequestconfig(httpget); try{ CloseableHttpResponse response = httpclient.execute(httpget); int statusOk = response.getStatusLine().getStatusCode(); if(logger.isInfoEnabled()){ logger.info(url+"result-statusCode=>>"+statusOk); } if(statusOk == HttpStatus.SC_OK){ HttpEntity entity = response.getEntity(); BufferedInputStream instream = new BufferedInputStream(entity.getContent()); byte[] chars = new byte[2048]; int len=0; while((len=instream.read(chars))!=-1){ sb.append(new String(chars,0,len)); } }else{ logger.error(url+"result->网络异常.."+statusOk); } if(logger.isInfoEnabled()){ logger.info(url+"result->"+sb.toString()); } }catch(Exception e){ e.printStackTrace(); }finally { httpget.releaseConnection(); try { httpclient.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return sb.toString(); }

java基础篇-模拟浏览器请求(post,get) 有更新!

public static String postRequest(String url, Map<String, String> data) {
		// 响应内容
		String result = "";

		// 定义http客户端对象--httpClient
		HttpClient httpClient = new HttpClient();

		// 定义并实例化客户端链接对象-postMethod
		PostMethod postMethod = new PostMethod(url);

		try {
			// 设置http的头
			postMethod.getParams().setParameter(
					HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
			postMethod.setRequestHeader("ContentType",
					"application/x-www-form-urlencoded;charset=UTF-8");
			if (data != null) {
				NameValuePair[] data1 = new NameValuePair[data.size()];
				int i = 0;
				for (String mapKey : data.keySet()) {
					// 填入各个表单域的值
					String vString = data.get(mapKey) == null ? "" : data.get(
							mapKey).toString();
					// vString = new String(vString.getBytes("utf-8"),"GBK");
					data1[i++] = new NameValuePair(mapKey, vString);
				}

				// 将表单的值放入postMethod中
				postMethod.setRequestBody(data1);
			}
			// 定义访问地址的链接状态
			int statusCode = 0;
			try {
				// 客户端请求url数据
				statusCode = httpClient.executeMethod(postMethod);
			} catch (Exception e) {
				e.printStackTrace();
			}

			// 请求成功状态-200
			if (statusCode == HttpStatus.SC_OK) {
				try {
					result = postMethod.getResponseBodyAsString();
				} catch (IOException e) {
					e.printStackTrace();
				}
			} else {
				System.out.println("请求返回状态:" + statusCode);
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			// 释放链接
			postMethod.releaseConnection();
			httpClient.getHttpConnectionManager().closeIdleConnections(0);
		}
		return result;
	}

	public static String postRequest(String url, String xmlstring,
			String contentType, String charset) {
		if (StringUtils.isBlank(charset)) {
			charset = "UTF-8";
		}
		if (StringUtils.isBlank(contentType)) {
			contentType = "text/html;charset=" + charset;
		}
		PostMethod post = new PostMethod(url);
		// 设置请求的内容直接从文件中读取
		HttpClient httpclient = new HttpClient();
		httpclient.getParams().setContentCharset("UTF-8");
		String resultstring = "";
		try {
			post.setRequestEntity(new StringRequestEntity(xmlstring,
					contentType, charset));
			int result = httpclient.executeMethod(post);
			resultstring = post.getResponseBodyAsString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		post.releaseConnection();
		return resultstring;
	}

	public static String postRequest(String url, Map<String, Object> data,
			Map<String, String> cookie, String domain) {
		// 响应内容
		String result = "";

		// 定义http客户端对象--httpClient
		HttpClient httpClient = new HttpClient();

		// 定义并实例化客户端链接对象-postMethod
		PostMethod postMethod = new PostMethod(url);

		try {
			// 设置http的头
			postMethod.getParams().setParameter(
					HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
			postMethod.setRequestHeader("ContentType",
					"application/x-www-form-urlencoded;charset=UTF-8");
			if (cookie != null) {
				if (domain == null) {
					domain = "";
				}
				HttpState initialState = new HttpState();
				for (String cookieName : cookie.keySet()) {
					Cookie c = new Cookie(domain, cookieName,
							cookie.get(cookieName), "/", -1, true);
					initialState.addCookie(c);
				}
				httpClient.setState(initialState);
			}
			if (data != null) {
				NameValuePair[] data1 = new NameValuePair[data.size()];
				int i = 0;
				for (String mapKey : data.keySet()) {
					// 填入各个表单域的值
					String vString = data.get(mapKey) == null ? "" : data.get(
							mapKey).toString();
					// vString = new String(vString.getBytes("utf-8"),"GBK");
					data1[i++] = new NameValuePair(mapKey, vString);
				}

				// 将表单的值放入postMethod中
				postMethod.setRequestBody(data1);
			}

			// 定义访问地址的链接状态
			int statusCode = 0;
			try {
				// 客户端请求url数据
				statusCode = httpClient.executeMethod(postMethod);
			} catch (Exception e) {
				e.printStackTrace();
			}

			// 请求成功状态-200
			if (statusCode == HttpStatus.SC_OK) {
				try {
					result = postMethod.getResponseBodyAsString();
				} catch (IOException e) {
					e.printStackTrace();
				}
			} else {
				System.out.println("请求返回状态:" + statusCode);
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			// 释放链接
			postMethod.releaseConnection();
			httpClient.getHttpConnectionManager().closeIdleConnections(0);
		}
		return result;
	}

java基础篇--模拟浏览器请求https--安全协议https请求 有更新!

https 协议,因为安全,所以在处理上,也有些不同。现在给出示例

 

/**
	 * @param url
	 * @param xmlstring
	 * @param match_id 密钥-- .p12的密钥
	 * @param file "apiclient_cert.p12" .p12的文件路径
	 * @return
	 */
	public static String httpsGetRequest(String url, String xmlstring, String match_id,String file){
		    KeyStore keyStore;
		    StringBuilder result = new StringBuilder();
			try {
				keyStore = KeyStore.getInstance("PKCS12");
				FileInputStream instream = new FileInputStream(new File(file));
	            keyStore.load(instream, match_id.toCharArray());

		        // Trust own CA and all self-signed certs
		        SSLContext sslcontext = SSLContexts.custom()
		                .loadKeyMaterial(keyStore, match_id.toCharArray())
		                .build();
		        // Allow TLSv1 protocol only
		        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
		                sslcontext,
		                new String[] { "TLSv1" },
		                null,
		                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
		        CloseableHttpClient httpclient = HttpClients.custom()
		                .setSSLSocketFactory(sslsf)
		                .build();
		        try {

	            HttpGet httpget = new HttpGet(url);
	            System.out.println("executing request" + httpget.getRequestLine());
	            CloseableHttpResponse response = httpclient.execute(httpget);
	            try {
	                HttpEntity entity = response.getEntity();
	                System.out.println("----------------------------------------");
	                System.out.println(response.getStatusLine());
	                if (entity != null) {
	                    System.out.println("Response content length: " + entity.getContentLength());
	                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
	                    String text="";
	                    while ((text = bufferedReader.readLine()) != null) {
	                    	result.append(text);
	                    }
	                }
	                EntityUtils.consume(entity);
	            } finally {
	                response.close();
	            }
	        } finally {
	            httpclient.close();
	        }
			} catch (Exception e) {
				e.printStackTrace();
			}
		return result.toString();
	}
	

公告

喧哗博客--繁华过后的沉寂--技术经验分享^-^
Copyright (c) 2009-2019, b3log.org & hacpai.com