在java程序开发中经常用到与服务端的交互工作,主要的就是传递相应的参数请求从而获取到对应的结果加以处理

可以使用Get请求与Post请求,注意!这里的Get请求不是通过浏览器界面而是在程序代码中设置的,达到Get请求的目的,具体请详见下列描述

以下get与post请求需要引入的包:

import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder; import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

Get请求:

/**
* 正常简易的使用HttpGet来向服务端发送Get请求传递的参数直接在url后面拼装上就可以了
* @param httpUrl
*/
public static String httpGet(String httpUrl){ httpUrl ="http://192.168.199.138/weixin/test.php?appid=appidaaaa&secret=secretbbbb";
HttpGet httpGet = new HttpGet(httpUrl);
CloseableHttpResponse chResponse = null;
String result = null;
try {
chResponse = HttpClients.createDefault().execute(httpGet);
if(chResponse.getStatusLine().getStatusCode()==200){
result = EntityUtils.toString(chResponse.getEntity());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(chResponse !=null){
try {
chResponse.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
if(result !=null){
System.out.println("有结果返回result=="+result);
return result;
}else{
System.out.println("请求没有结果返回");
return "";
}
} /**
* 显示的来调用HttpGet这里的发送执行execut与上面简易方法有不同,
* 传递的参数直接拼装在url上传递即可
* @param httpUrl
* @return
*/
@SuppressWarnings("deprecation")
public static String httpGetShow(String httpUrl){ //httpUrl = "";
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response =null;
String result = null;
try { //发送get请求
HttpGet httpGet = new HttpGet(httpUrl); //不同之处
response= client.execute(httpGet);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(response.getEntity());
httpUrl = URLDecoder.decode(httpUrl, "UTF-8");
}
} catch (IOException e) {
e.printStackTrace();
}finally {
client.close();
}
if(result !=null){
return result;
}else{
return "";
}
}

Post请求:

/**
* 不显示的使用HttpPost就会默认提交请求的方式为post,
* 传递的参数为以key:value的形式来传递参数
* @param httpUrl
* @param imagebyte 可以传递图片等文件,以字节数组的形式传递
*/
@SuppressWarnings({ "deprecation" })
public static String httpPost(String httpUrl,byte[] imagebyte){ httpUrl="http://192.168.199.138/weixin/test.php";
HttpPost httpPost = new HttpPost(httpUrl);
ByteArrayBody image = new ByteArrayBody(imagebyte,ContentType.APPLICATION_JSON,"image.jpg");//传递图片的时候可以通过此处上传image.jpg随便给出即可 String appid = "appid";
String secret = "secret"; StringBody appidbody = new StringBody(appid,ContentType.APPLICATION_JSON);
StringBody secretbody = new StringBody(secret,ContentType.APPLICATION_JSON);
MultipartEntityBuilder me = MultipartEntityBuilder.create();
me.addPart("image", image)//image参数为在服务端获取的key通过image这个参数可以获取到传递的字节流,这里不一定就是image,你的服务端使用什么这里就对应给出什么参数即可
.addPart("appid",appidbody )
.addPart("secret", secretbody); DefaultHttpClient client= new DefaultHttpClient();
HttpEntity reqEntity = me.build();
httpPost.setEntity(reqEntity);
HttpResponse responseRes = null;
try {
responseRes=client.execute(httpPost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
client.close();
} int status = responseRes.getStatusLine().getStatusCode();
String resultStr =null;
if (status == 200) {
byte[] content;
try {
content = getContent(responseRes);
resultStr = new String(content,"utf-8");
System.out.println("httpPost返回的结果==:"+resultStr);
} catch (IOException e) {
e.printStackTrace();
}
} if(resultStr !=null){
return resultStr;
}else{
return "";
}
} /**
* 显示的调用HttpPost来使用post方式提交请求,并且将请求的参数提前拼装成json字符串,
* 直接使用StringEntity来发送参数不必要再使用key:value的形式来设置请求参数,
* 在服务端使用request.getInputStream()来把request中的发送过来的json字符串解析出来,
* 就是因为使用StringEntity来包装了传递的参数
* @param httpUrl
* @param jsonParam
*/
@SuppressWarnings({ "resource", "deprecation" })
public static String httpPostShow(String httpUrl,String jsonParam){ httpUrl="http://192.168.199.138/weixin/test.php";
jsonParam="{\"appid\":\"appidbbbb33333\",\"secret\":\"secretaaaaa3333\"}";//拼装一个json串 DefaultHttpClient httpClient = new DefaultHttpClient(); //这里就是显示的调用post来设置使用post提交请求
HttpPost method = new HttpPost(httpUrl);
String result = null;
try {
if (null != jsonParam) {
//解决中文乱码问题
StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");//这个StringEntity可以在服务端不用key:value形式来接收,可以request.getInputStream()来获取处理整个请求然后解析即可
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
method.setEntity(entity);
}
HttpResponse response = httpClient.execute(method);
httpUrl = URLDecoder.decode(httpUrl, "UTF-8");
if (response.getStatusLine().getStatusCode() == 200) {
try {
result = EntityUtils.toString(response.getEntity());
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
if(result !=null){
return result;
}else{
return "";
}
} private static byte[] getContent(HttpResponse response)
throws IOException {
InputStream result = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = resEntity.getContent();
int len = 0;
while ((len = result.read()) != -1) {
out.write(len);
}
return out.toByteArray();
}
} catch (IOException e) {
e.printStackTrace();
throw new IOException("getContent异常", e);
} finally {
out.close();
if (result != null) {
result.close();
}
}
return null;
}

以上为java中http的get与post请求方式,httpPost(String httpUrl,byte[] imagebyte)这个方法可以传递图片等非结构化数据,以流的形式传递。

java-HttpGetPost-图片字节流上传的更多相关文章

  1. java实现图片的上传和展示

    一.注意事项: 1,该项目主要采用的是springboot+thymeleaf框架 2,代码展示的为ajax完成图片上传(如果不用ajax只需要改变相应的form表单配置即可) 二.效果实现: 1,页 ...

  2. java模拟表单上传文件,java通过模拟post方式提交表单实现图片上传功能实例

    java模拟表单上传文件,java通过模拟post方式提交表单实现图片上传功能实例HttpClient 测试类,提供get post方法实例 package com.zdz.httpclient; i ...

  3. 【转载】【JAVA秒会技术之图片上传】基于Nginx及FastDFS,完成图片的上传及展示

    基于Nginx及FastDFS,完成商品图片的上传及展示 一.传统图片存储及展示方式 存在问题: 1)大并发量上传访问图片时,需要对web应用做负载均衡,但是会存在图片共享问题 2)web应用服务器的 ...

  4. 利用WebUploader进行图片批量上传,在页面显示后选择多张图片压缩至指定路径【java】

    WebUploader是由Baidu WebFE(FEX)团队开发的一个简单的以HTML5为主,FLASH为辅的现代文件上传组件.在现代的浏览器里面能充分发挥HTML5的优势,同时又不摒弃主流IE浏览 ...

  5. Java FtpClient 实现文件上传服务

    一.Ubuntu 安装 Vsftpd 服务 1.安装 sudo apt-get install vsftpd 2.添加用户(uftp) sudo useradd -d /home/uftp -s /b ...

  6. springmvc图片文件上传接口

    springmvc图片文件上传 用MultipartFile文件方式传输 Controller package com.controller; import java.awt.image.Buffer ...

  7. HTTP请求中的Body构建——.NET客户端调用JAVA服务进行文件上传

    PS:今日的第二篇,当日事还要当日毕:)   http的POST请求发送的内容在Body中,因此有时候会有我们自己构建body的情况. JAVA使用http—post上传file时,spring框架中 ...

  8. java微信接口之四—上传素材

    一.微信上传素材接口简介 1.请求:该请求是使用post提交地址为: https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=A ...

  9. asp.net+swfupload 多图片批量上传(附源码下载)

    asp.net的文件上传都是单个文件上传方式,无法执行一次性多张图片批量上传操作,要实现多图片批量上传需要借助于flash,通过flash选取多个图片(文件),然后再通过后端服务进行上传操作. 本次教 ...

  10. 【原创】用JAVA实现大文件上传及显示进度信息

    用JAVA实现大文件上传及显示进度信息 ---解析HTTP MultiPart协议 (本文提供全部源码下载,请访问 https://github.com/grayprince/UploadBigFil ...

随机推荐

  1. I、Python 环境搭建

    I.安装Python https://www.python.org/downloads/windows/ 下载路径总是变,认准那个名字 安装, 记住,所有语言都推荐安装在 默认路径,不要相信那些让你改 ...

  2. C# lambda 和 Linq

    本章节给大家带来的是Lambda 和 Linq 的关系 Lambda : 是实例化委托的一个参数,也就是一个方法 Linq:是基于委托(lambda)的封装,代码重用,逻辑解耦,是一个帮助类库,lin ...

  3. maven多模块部署(转载)

    [Maven]使用Maven构建多模块项目 Maven多模块项目 Maven多模块项目,适用于一些比较大的项目,通过合理的模块拆分,实现代码的复用,便于维护和管理.尤其是一些开源框架,也是采用多模块的 ...

  4. office365离线安装

    office版本是在线安装,每次安装比较麻烦,所以还是离线安装合适,这里推荐一篇博文https://www.cnblogs.com/Devopser/p/7919245.html 但是由于部署工具变化 ...

  5. Ubuntu18.04安装mysql及相关配置

    step 1: sudo apt-get update step 2: sudo apt-get install mysql-server step3: 查看mysql服务端是否开启 systemct ...

  6. urllib库使用方法 3 get html

    import urllib.requestimport urllib.parse #https://www.baidu.com/s?ie=UTF-8&wd=中国#将上面的中国部分内容,可以动态 ...

  7. 树莓派3B+学习笔记:8、安装MySQL

    1.打开终端,先执行: sudo apt-get update 2.再执行: sudo apt-get install mysql-server 输入“y”确认并回车 3.初始化MySQL,输入: s ...

  8. coinmarketcap.com爬虫

    coinmarketcap.com爬虫 写的真是蛋疼 # -*- coding:utf-8 -*- import requests from lxml import etree headers = { ...

  9. (数据科学学习手札55)利用ggthemr来美化ggplot2图像

    一.简介 R中的ggplot2是一个非常强大灵活的数据可视化包,熟悉其绘图规则后便可以自由地生成各种可视化图像,但其默认的色彩和样式在很多时候难免有些过于朴素,本文将要介绍的ggthemr包专门针对原 ...

  10. 为树莓派添加一个强实时性前端[原创cnblogs.com/helesheng]

    树莓派是最近流行嵌入式平台,其自由的开源特性以及低廉的价格,吸引了来 自全球的大量极客和计算机大咖的关注.来自各大树莓派社区的幕后英雄,无私地在这个开源硬件平台上做了大量的工作,将其打造成了世界上通用 ...