在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. zabbix3.0通过yum安装笔记

    zabbix3.0通过yum安装笔记 一.通过yum安装zabbix rpm -Uvh https://repo.zabbix.com/zabbix/3.0/rhel/7/x86_64/zabbix- ...

  2. 虚拟机重启网络服务失败,当查看状态显示错误Failed to start LSB......

    重启网络失败截图 从本质上来看出现这样的问题,是因为拷贝过来的虚拟机重新分配了网卡MAC地址.这样造成的结果是配置文件中MAC与当前网卡MAC不一致.所以只需要修改一下配置文件即可. 用ip addr ...

  3. jq写无缝轮播

    今天分享一下我自己早几天写的一个效果:无缝轮播,虽然不难,很简单,也没有封装处理过,但是还是希望能帮到一些前端的小伙伴吧,如果有小伙伴感觉有更简化的写法希望可以一起交流一下,技术在于交流嘛,我的邮箱是 ...

  4. Node.js http.createServer 简单服务配置

    基本实现: var http = require("http"); var server = http.createServer(function (req, res) { if ...

  5. 嵌入式nand flash详解

    一.s3c2440启动后会将nand flash的前4K程序复制到内部的sram中,这个过程是硬件自动完成的,但是如果我们的程序远远大于4K,这个时候就需要将程序从flash拷贝到内存中来运行了. 二 ...

  6. [FreeRTOS入门] 1.CubeMX中FreeRTOS配置参数及理解

    1.有关优先级 1.1 Configuration --> FreeRTOS MAX_PRIORITIES 设置任务优先级的数量:配置应用程序有效的优先级数目.任何数量的任务都可以共享一个优先级 ...

  7. 排序 permutation

    习题2-6 排序 permutation 用1,2,3……9组成3个三位数abc,def和ghi,每个数字恰好使用一次,要求abc:def:ghi=1:2:3.按照“abc def ghi”的格式输出 ...

  8. Codeforces #123D: 后缀数组+单调栈

    D. String     You are given a string s. Each pair of numbers l and r that fulfill the condition 1 ≤  ...

  9. Websocket 临时参考网站

    https://blog.csdn.net/SGuniver_22/article/details/74273839 https://www.zhihu.com/question/20215561 h ...

  10. 20155308 2016-2017-2 《Java程序设计》实验二 Java面向对象程序设计

    20155308 2016-2017-2 <Java程序设计>实验二 Java面向对象程序设计 实验内容 初步掌握单元测试和TDD 理解并掌握面向对象三要素:封装.继承.多态 初步掌握UM ...