以流的形式发送请求
package com.ckn.web.main;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;
import javax.net.ssl.HttpsURLConnection;
public class Test2 {
public static final String JSON_ENCODE="UTF-8";
public static String post(String url,String json) {
String respText=null;
try{
//1、重新对请求报文进行 UTF-8 编码
byte[] postData=null;
postData=json.getBytes(JSON_ENCODE);
//2、发送 HTTP/HTTPS 请求
OutputStream reqStream=null;
InputStream resStream=null;
URLConnection urlCon=null;
// A、与服务器建立 HTTP/HTTPS 连接
urlCon=Test2.createRequest(url, "POST");
// B、指定报文头 [Content-type]、[Content-length]、[Keep-alive]
urlCon.setRequestProperty("Content-type", "application/json;charset="+JSON_ENCODE);
urlCon.setRequestProperty("Content-length", String.valueOf(postData.length));
urlCon.setRequestProperty("Keep-alive", "false");
// C、获取与服务器的输出流、然后向服务器写数据
reqStream=urlCon.getOutputStream();
reqStream.write(postData);
reqStream.flush();
reqStream.close();
// D、接收服务器返回结果
ByteArrayOutputStream ms=null;
resStream=urlCon.getInputStream();
ms=new ByteArrayOutputStream();
byte[] buf=new byte[4096];
int count;
while((count=resStream.read(buf, 0, buf.length))>0){
ms.write(buf, 0, count);
}
resStream.close();
respText=new String(ms.toByteArray(),JSON_ENCODE);
}catch(Exception e2){
e2.printStackTrace();
}
return respText;
}
protected static URLConnection createRequest(String urlStr, String strMethod) throws Exception{
//根据 URL 获取一个到主机连接
URLConnection conn= Test2.getRequestByUrl(urlStr);
//判断该连接是否 HTTP 连接
if(conn instanceof HttpsURLConnection || !(conn instanceof HttpURLConnection)){
throw new RuntimeException("URL 无法建立 HTTP 连接:"+urlStr);
}
//设置HTTP相关配置:提交方式
HttpURLConnection httpConn=(HttpURLConnection) conn;
httpConn.setRequestMethod(strMethod);
return conn;
}
/**
* 获取URLConnection
* @param urlStr
* @return
* @throws MalformedURLException
*/
public static URLConnection getRequestByUrl(String urlStr) throws Exception{
URL url=null;
URLConnection conn=null;
url=new URL(urlStr);
conn=url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
return conn;
}
public static void main(String[] args){
String url="http://127.0.0.1:8088/app-zht/ex/api.do?reqType=effecDateAndEndDate";
String json="[\"SHZVJ6SMHZ9U5TCLL\",\"SHZVJ6SMHZ9U5TCLL\",\"S0000000000000003\"]";
String r=post(url,json);
System.out.println(r);
}
}