分享者:低调小虾米 调用产生二维码的接口一直乱码,一直没想出为什么乱码,囧,郁闷之极,还好九爷慷慨分享了文章,得知返回的是二进制,createwxaqrcode接口并不复杂,只是在官方接口并没声明返回内容,只要知道返回的内容就好办了,代码如下 post请求 public static String httpPostWithJSON(String url, String json)
throws Exception {
String result = null;
// 将JSON进行UTF-8编码,以便传输中文
String encoderJson = URLEncoder.encode(json, HTTP.UTF_8);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
StringEntity se = new StringEntity(json);
se.setContentType(CONTENT_TYPE_TEXT_JSON);
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
APPLICATION_JSON));
httpPost.setEntity(se);
// httpClient.execute(httpPost);
HttpResponse response = httpClient.execute(httpPost);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
InputStream instreams = resEntity.getContent();
saveToImgByInputStream(instreams, "D:\\", "apr.jpg");
}
}
return result;
}
将二进制转换成文件保存 /**
* 将二进制转换成文件保存
* @param instreams 二进制流
* @param imgPath 图片的保存路径
* @param imgName 图片的名称
* @return
* 1:保存正常
* 0:保存失败
*/
public static int saveToImgByInputStream(InputStream instreams,String imgPath,String imgName){
int stateInt = 1;
if(instreams != null){
try {
File file=new File(imgPath,imgName);//可以是任何图片格式.jpg,.png等
FileOutputStream fos=new FileOutputStream(file);
byte[] b = new byte[1024];
int nRead = 0;
while ((nRead = instreams.read(b)) != -1) {
fos.write(b, 0, nRead);
}
fos.flush();
fos.close();
} catch (Exception e) {
stateInt = 0;
e.printStackTrace();
} finally {
}
}
return stateInt;
}
相关主题:跳坑指南《八十五》带参数二维码,返回数据保存为图片 |