Java发送HTTP POST请求示例

时间:2021-04-17 13:24:22

概述:

http请求在所有的编程语言中几乎都是支持的,我们常用的两种为:GET,POST请求。一般情况下,发送一个GET请求都很简单,因为参数直接放在请求的URL上,所以,对于PHP这种语言,甚至只需要一行:file_get_content(url);就能完成数据的获取,但对于POST请求,由于其数据是在消息体中发送出去的,所以相对来说要麻烦一点,再涉及到需要发送文件等二进制的数据类型,就更需要更多的处理,下面我们用Java语言来实现POST请求发送数据,其他语言类似。

public class MainUI {

    private static final String REQUEST_PATH = "http://localhost/server_url.php";
private static final String BOUNDARY = "20140501"; /**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub URL url = new URL(REQUEST_PATH);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setConnectTimeout(3000); // 设置发起连接的等待时间,3s
httpConn.setReadTimeout(30000); // 设置数据读取超时的时间,30s
httpConn.setUseCaches(false); // 设置不使用缓存
httpConn.setDoOutput(true);
httpConn.setRequestMethod("POST"); httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
OutputStream os = httpConn.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(os); String content = "--" + BOUNDARY + "\r\n";
content += "Content-Disposition: form-data; name=\"title\"" + "\r\n\r\n";
content += "我是post数据的值";
content += "\r\n--" + BOUNDARY + "\r\n";
content += "Content-Disposition: form-data; name=\"cover_img\"; filename=\"avatar.jpg\"\r\n";
content += "Content-Type: image/jpeg\r\n\r\n";
bos.write(content.getBytes()); // 开始写出文件的二进制数据
FileInputStream fin = new FileInputStream(new File("avatar.jpg"));
BufferedInputStream bfi = new BufferedInputStream(fin);
byte[] buffer = new byte[4096];
int bytes = bfi.read(buffer, 0, buffer.length);
while (bytes != -1) {
bos.write(buffer, 0, bytes);
bytes = bfi.read(buffer, 0, buffer.length);
}
bfi.close();
fin.close();
bos.write(("\r\n--" + BOUNDARY).getBytes());
bos.flush();
bos.close();
os.close(); // 读取返回数据
StringBuffer strBuf = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
strBuf.append(line).append("\n");
}
String res = strBuf.toString();
System.out.println(res);
reader.close();
httpConn.disconnect();
} }

下面,对上述的代码做一些必要的说明:

http发送的post数据是通过boundary和换行符来分割的,boundary是一个随机的字符串即可,但不要与你传递的参数名或参数值相同。

换行符要求也是比较严格的,数据的声明和数据的值之间需要两个换行符,两个数据之间要用boundary来划分。对于二进制的数据来说,只是参数的类型声明和普通的数据有点区别,比如上述的代码增加了filename和content-type,二进制的数据以字符流写出去就行了。