Java 利用HttpURLConnection发送http请求
写了一个简单的 Http 请求的Class,实现了 get, post ,postfile
package com.asus.uts.util; import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL; /**
* Created by jiezhou on 16/2/22.
*/
public class HttpHelper {
public static void main(String[] args) throws JSONException{
JSONObject json = new JSONObject();
json.put("un", "bruce");
json.put("pwd", "123456"); //get
request r = get("http://127.0.0.1:5000/index/user/1/m", json);
System.out.println(r.status_code);
System.out.println(r.text); //post json data
String s = "{'sex': 'm', 'name': '', 'id': 1}";
JSONObject json2 = new JSONObject(s);
request r2 = post("http://127.0.0.1:5000/index/user/1/m", json2);
//post File
String path = "/Users/jiezhou/Documents/test.py";
postFile("http://127.0.0.1:5000/fileupload", "temp.txt", "/Users/jiezhou/Documents/temp.txt");
}
/**
* 请求返回的对象
* @author jiezhou
*
*/
public static class request{
//状态码
public int status_code;
//返回数据
public String text;
}
private HttpHelper(){
}
/**
* 从服务器get 数据
* @param getUrl URL地址
* @param params JSONObject类型的数据格式
* @return request
*/
public static request get(String getUrl, JSONObject params){
request r = new request();
HttpURLConnection conn = null;
try {
//拼接参数
if (params != null) {
String per = null;
for (int i=0; i< params.names().length(); i++){
per = i == 0? "?" : "&";
getUrl += per + params.names().get(i).toString() + "=" + params.get(params.names().get(i).toString());
}
}
URL url = new URL(getUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5000);
conn.setConnectTimeout(10000);
int status_code = conn.getResponseCode();
r.status_code = status_code;
if (status_code == 200){
InputStream is = conn.getInputStream();
r.text = getStringFromInputStream(is);
}
} catch (Exception e) {
}
return r;
}
/**
* post 数据
* @param getUrl URL地址
* @param params JSONObject类型的数据格式
* @return request
*/
public static request post(String getUrl, JSONObject params){
request r = new request();
HttpURLConnection conn = null;
try {
URL url = new URL(getUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setReadTimeout(5000);
conn.setConnectTimeout(10000);
conn.setDoOutput(true);// 设置此方法,允许向服务器输出内容
// post请求的参数
String data = null;
//拼接参数
if (params != null) {
data = params.toString();
}
// 获得一个输出流,向服务器写数据,默认情况下,系统不允许向服务器输出内容
OutputStream out = conn.getOutputStream();// 获得一个输出流,向服务器写数据
out.write(data.getBytes());
out.flush();
out.close();
int status_code = conn.getResponseCode();
r.status_code = status_code;
if (status_code == 200){
InputStream is = conn.getInputStream();
r.text = getStringFromInputStream(is);
}
} catch (Exception e) {
System.out.println(e.getMessage().toString());
}
return r;
}
/**
* post上传文件
* @param getUrl url 地址
* @param fileName 文件名
* @param filePath 文件路径
* @return request
*/
public static request postFile(String getUrl, String fileName, String filePath){
request r = new request();
HttpURLConnection conn = null;
try {
String end = "\r\n";
String twoHyphens = "--";
String boundary = "******"; // 定义数据分隔线
URL url = new URL(getUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);// 设置此方法,允许向服务器输出内容
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setReadTimeout(5000);
conn.setConnectTimeout(10000);
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
// post请求的参数
DataOutputStream ds = new DataOutputStream(conn.getOutputStream());
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data; "
+ "name=\"file\";filename=\"" + fileName + "\"" + end);
ds.writeBytes(end);
/* 取得文件的FileInputStream */
FileInputStream fStream = new FileInputStream(filePath);
/* 设置每次写入1024bytes */
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
/* 从文件读取数据至缓冲区 */
while ((length = fStream.read(buffer)) != -1) {
/* 将资料写入DataOutputStream中 */
ds.write(buffer, 0, length);
}
ds.writeBytes(end);
ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
/* close streams */
fStream.close();
ds.flush();
int status_code = conn.getResponseCode();
r.status_code = status_code;
if (status_code == 200){
InputStream is = conn.getInputStream();
r.text = getStringFromInputStream(is);
}
} catch (Exception e) {
System.out.println(e.getMessage().toString());
}
return r;
}
/**
* 装换InputStream
* @param is
* @return
* @throws IOException
*/
private static String getStringFromInputStream(InputStream is) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
// 模板代码 必须熟练
byte[] buffer = new byte[1024];
int len = -1;
// 一定要写len=is.read(buffer)
// 如果while((is.read(buffer))!=-1)则无法将数据写入buffer中
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
is.close();
String state = os.toString();// 把流中的数据转换成字符串,采用的编码是utf-8(模拟器默认编码)
os.close();
return state;
}
}
Java 利用HttpURLConnection发送http请求的更多相关文章
- 利用HttpURLConnection发送post请求上传多个文件
本文要用java.net.HttpURLConnection来实现多个文件上传 1. 研究 form 表单到底封装了什么样的信息发送到servlet. 假如我参数写的内容是hello word,然后二 ...
- HttpURLConnection 发送http请求帮助类
java 利用HttpURLConnection 发送http请求 提供GET / POST /上传文件/下载文件 功能 import java.io.*; import java.net.*; im ...
- HttpUrlConnection发送url请求(后台springmvc)
1.HttpURLConnection发送url请求 public class JavaRequest { private static final String BASE_URL = "h ...
- HttpURLConnection发送POST请求(可包含文件)
import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; import java.io. ...
- JAVA利用HttpClient进行POST请求(HTTPS)
目前,要为另一个项目提供接口,接口是用HTTP URL实现的,最初的想法是另一个项目用jQuery post进行请求. 但是,很可能另一个项目是部署在别的机器上,那么就存在跨域问题,而JQuery的p ...
- java 模拟浏览器发送post请求
java使用URLConnection发送post请求 /** * 向指定 URL 发送POST方法的请求 * * @param url * 发送请求的 URL * @param param * 请求 ...
- Java利用原始HttpURLConnection发送http请求数据小结
1,在post请求下,写输出应该在读取之后,否则会抛出异常. 即操作OutputStream对象应该在InputStreamReader之前. 2.conn.getResponseCode()获取返回 ...
- 【JAVA】通过URLConnection/HttpURLConnection发送HTTP请求的方法(一)
Java原生的API可用于发送HTTP请求 即java.net.URL.java.net.URLConnection,JDK自带的类: 1.通过统一资源定位器(java.net.URL)获取连接器(j ...
- 利用HttpURLConnection发送请求
HttpURLConnection: 每个 HttpURLConnection实例都可用于生成单个请求,但是其他实例可以透明地共享连接到 HTTP 服务器的基础网络.请求后在 HttpURLConne ...
随机推荐
- 真机调试时遇到“Could not launch *** process launch failed: Security”的解决办法
半年没写ios程序了,打算重新将这块技术捡回来.谁知道写的第一个测试程序在真机上就跑出来因为安全问题不能加载的情况. ios的版本是9.2的.看提示信息是app的启动被ios的安全机制阻挡了. 在手机 ...
- [转载]ARM协处理器CP15寄存器详解
用于系统存储管理的协处理器CP15 原地址:http://blog.csdn.net/gameit/article/details/13169405 MCR{cond} coproc,opc ...
- TensorFlow中权重的随机初始化
一开始没看懂stddev是什么参数,找了一下,在tensorflow/python/ops里有random_ops,其中是这么写的: def random_normal(shape, mean=0.0 ...
- ActiveX控件打包、签名、嵌入详解
ActiveX控件打包.签名.嵌入详解 前言 在我们的一个项目中,使用到了大华网络监控摄像头枪机,网络上下载了其ActiveX插件,但是发现其所提供的类库没有打包处理.这就导致我们每次给用户安装的时候 ...
- sqlmap用户手册
http://192.168.136.131/sqlmap/mysql/get_int.php?id=1 当给sqlmap这么一个url的时候,它会: 1.判断可注入的参数2.判断可以用那种SQL注入 ...
- 编译WebRTC遇到的问题总结
唉,本人下载WebRTC的代码都用了几天,真的是惭愧,本来以为很简单的东西,没想到搞了这么久,在下载的过程中,心里骂了无数遍XXX,这鬼东西咋这么难搞.后来终于搞明白了为啥代码总是下载不了,然后又在心 ...
- maven导入本地jar包
<dependency> <groupId>com.qrcode</groupId> <artifactId>qrcode</artifactId ...
- jquery文件上传
http://www.jb51.net/Special/799.htm http://www.oschina.net/project/tag/356/jquery-file-upload
- pom.xml详解
setting.xml主要用于配置maven的运行环境等一系列通用的属性,是全局级别的配置文件:而pom.xml主要描述了项目的maven坐标,依赖关系,开发者需要遵循的规则,缺陷管理系统,组织和li ...
- Google黑板报: 数学之美系列(网上找的原链接)
转载地址:http://blog.sina.com.cn/s/blog_47cccb02010009u0.html 系列一 -- 统计语言模型 http://googlechinablog.com/2 ...