写了一个简单的 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. vc++>>Connection using old (pre-4.1.1) authentication protocol refused (client option 'secure_auth' enable

    用VC来连接远程MYSQL时,出现如标题一样的错误,网上搜索了此错误产生的原因,最后自己找到了解决办法. 此错误产生的原因: 异常原因在于服务器端的密码管理协议陈旧,使用的是旧有的用户密码格式存储:但 ...

  2. Random

    /* * Random:产生随机数的类 * * 构造方法: * public Random():没有给种子,用的是默认种子,是当前时间的毫秒值 * public Random(long seed):给 ...

  3. Disruptor 极速体验

    已经不记得最早接触到 Disruptor 是什么时候了,只记得发现它的时候它是以具有闪电般的速度被介绍的.于是在脑子里, Disruptor 和"闪电"一词关联了起来,然而却一直没 ...

  4. Underscore.js基础入门

    公司产品集成了对Underscore.js,所以需要对这个库有一定的了解.通过查阅资料,发现这个库主是对Array和JSON的处理支持.通过Underscore.js库,可以方便的对Array和JSO ...

  5. LeetCode 374. Guess Number Higher or Lower

    We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to gues ...

  6. (转)设计模式_Singleton单例模式

    静态初始化 public sealed class Singleton { private static readonly Singleton instance = new Singleton(); ...

  7. [python实现设计模式]-4.观察者模式-吃食啦!

    观察者模式是一个非常重要的设计模式. 我们先从一个故事引入. 工作日的每天5点左右,大燕同学都会给大家订饭. 然后7点左右,饭来了. 于是燕哥大吼一声,“饭来啦!”,5点钟定过饭的同学就会纷纷涌入餐厅 ...

  8. SQLServer异步调用,批量复制

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  9. 《从零开始做一个MEAN全栈项目》(4)

    欢迎关注本人的微信公众号"前端小填填",专注前端技术的基础和项目开发的学习. 在上一篇中,我们讲了如何去构建第一个Express项目,总结起来就是使用两个核心工具,express和 ...

  10. Linux:添加永久路由

    没有以下文件时,可创建 vim /etc/sysconfig/network-scripts/route-eth0添加如下信息:192.168.142.100/32 via 192.168.142.1 ...