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 ...
随机推荐
- 开源共享一个训练好的中文词向量(语料是维基百科的内容,大概1G多一点)
使用gensim的word2vec训练了一个词向量. 语料是1G多的维基百科,感觉词向量的质量还不错,共享出来,希望对大家有用. 下载地址是: http://pan.baidu.com/s/1boPm ...
- FlashBuilder 新建项目时提示 java.lang.nullpointerexception
可以尝试安装 Air SDK
- Tplink客户端设置
之前在JD上面买了个Tplink,将公司的无线网转成有线的给我的台式机用,可是突然就掉线了,怎么配置都不行.甚至按向导去做了,后来连配置界面都进不去.然后又再某宝上面买了两个,回来配置也发现了这个情况 ...
- EventBus--出现的问题
--- 1 , EventBus收不到消息问题. 项目中遇到的问题,做搜索商品的时候遇到, 1.情况是一个FragmentActivity包含四个碎片Fragment,在FragmentActivit ...
- openssl生成ssl证书
openssl生成ssl证书 x509证书一般会用到三类文,key,csr,crt. Key 是私用密钥openssl格,通常是rsa算法. Csr 是证书请求文件,用于申请证书.在制作csr文件的时 ...
- WIN7 OEM Nin1 地址
WIN7 SP1 OEM Nin1 201205 一.映像版本列表 Windows 7 旗舰版 32位 LENOVOWindows 7 旗舰版 32位 ASUSWindows 7 旗舰版 32位 AC ...
- NPOI Excel 单元格背景颜色对照表
NPOI Excel 单元格颜色对照表,在引用了 NPOI.dll 后可通过 ICellStyle 接口的 FillForegroundColor 属性实现 Excel 单元格的背景色设置,FillP ...
- sqlserver ,left join 不仅可以join表,还可以是一个结果集
SELECT MA.NAME AS MakeName , M.ID AS ModelId , M.Name AS ModelName , M.Warranty AS ModelWarranty , S ...
- Linux中exit与_exit的区别
在exit,_exit的区别 - exit()与_exit()函数的区别(Linux系统中)2012-03-20 15:19:53 分类: LINUX 注:exit()就是退出,传入的参数是程序退出时 ...
- showModalDialog 的重要提示
模态对话框,没有opener,不能用window.opener.location.reload();或window.parent.location.reload();要通过返回值来判断关闭后刷新. f ...