写了一个简单的 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请求的更多相关文章

  1. 利用HttpURLConnection发送post请求上传多个文件

    本文要用java.net.HttpURLConnection来实现多个文件上传 1. 研究 form 表单到底封装了什么样的信息发送到servlet. 假如我参数写的内容是hello word,然后二 ...

  2. HttpURLConnection 发送http请求帮助类

    java 利用HttpURLConnection 发送http请求 提供GET / POST /上传文件/下载文件 功能 import java.io.*; import java.net.*; im ...

  3. HttpUrlConnection发送url请求(后台springmvc)

    1.HttpURLConnection发送url请求 public class JavaRequest { private static final String BASE_URL = "h ...

  4. HttpURLConnection发送POST请求(可包含文件)

    import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; import java.io. ...

  5. JAVA利用HttpClient进行POST请求(HTTPS)

    目前,要为另一个项目提供接口,接口是用HTTP URL实现的,最初的想法是另一个项目用jQuery post进行请求. 但是,很可能另一个项目是部署在别的机器上,那么就存在跨域问题,而JQuery的p ...

  6. java 模拟浏览器发送post请求

    java使用URLConnection发送post请求 /** * 向指定 URL 发送POST方法的请求 * * @param url * 发送请求的 URL * @param param * 请求 ...

  7. Java利用原始HttpURLConnection发送http请求数据小结

    1,在post请求下,写输出应该在读取之后,否则会抛出异常. 即操作OutputStream对象应该在InputStreamReader之前. 2.conn.getResponseCode()获取返回 ...

  8. 【JAVA】通过URLConnection/HttpURLConnection发送HTTP请求的方法(一)

    Java原生的API可用于发送HTTP请求 即java.net.URL.java.net.URLConnection,JDK自带的类: 1.通过统一资源定位器(java.net.URL)获取连接器(j ...

  9. 利用HttpURLConnection发送请求

    HttpURLConnection: 每个 HttpURLConnection实例都可用于生成单个请求,但是其他实例可以透明地共享连接到 HTTP 服务器的基础网络.请求后在 HttpURLConne ...

随机推荐

  1. OAF_开发系列29_实现OAF中批次处理迭代器RowSet/RowSetIterator(案例)

    20150814 Created By BaoXinjian

  2. Codeforces Round #381 (Div. 2)D. Alyona and a tree(树+二分+dfs)

    D. Alyona and a tree Problem Description: Alyona has a tree with n vertices. The root of the tree is ...

  3. 获得、修改 SQL Server表字段说明

    SELECT ( then d.name else '' end) 表名, a.colorder 字段序号, a.name 字段名, g.[value] AS 字段说明 FROM syscolumns ...

  4. 关于Android 打开新的Activity 虚拟键盘的弹出与不弹出

    关于Android 打开新的Activity 虚拟键盘的弹出与不弹出 打开Activity 时  在相应的情况 弹出虚拟键盘 或者 隐藏虚拟键盘 会给用户非常好的用户体验 , 实现起来也比较简单 只需 ...

  5. 使用Dapper读取Oracle多个结果集

    Dapper对SQL Server支持很好,但对于Oracle有些用法不一样,需要自己进行特殊处理. 1.首先要自定义一个Oracle参数类 public class OracleDynamicPar ...

  6. js 循环

    //数组循环var a = [1, 2, 3, 4, 5, 6];for (var i = 0, l = a.length; i < l; i++) { console.log(a[i]);} ...

  7. ScrollView左右约束的坑

    问题:因为要适配iPad,有些页面拉伸会很难看,需要适配成下图样子,但是按照比例调整了ScrollView左右间距之后出现左右可以滑动,设置contentSize的X为0 不起作用,   之后多番尝试 ...

  8. Xcode 8 在XIB中布局View尺寸1000*1000

    Xcode 8 中XIB布局变动,在界面未展示之前,所有的View的布局都会给一个1000*1000的初始值,查看视图层级可以看到View拖得很长, 有时候我们在ViewDidLoad中布局的时候会使 ...

  9. C# .NET 基本概念

    1. private. protected. public. internal 修饰符的访问权限.   private : 私有成员, 在类的内部才可以访问.    protected : 保护成员, ...

  10. Thinkphp的单字母函数整理

    有人不太喜欢TP这种单字母函数,其实这也是TP的一个特色,如果理解了这些函数的作用,不管是背,还是写,都是非常方便的,接下来我们以字母顺序开始.A函数 B函数 C函数 D函数 F函数 L函数 R函数 ...