如果用框架有很多选择,但有时候假如只是小测试,可以考虑用java原生库
import java.net.HttpURLConnection;
下面是get和post访问方法
public static String toUrl(String path, String method, String data) {
System.out.println(path);
System.out.println(data);
StringBuilder sb = new StringBuilder();
try {
URL url = new URL(path);
//打开和url之间的连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
/**设置URLConnection的参数和普通的请求属性****start***/
//设置是否向httpUrlConnection输出,设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
conn.setDoOutput(true);
conn.setDoInput(true);
//GET和POST必须全大写
conn.setRequestMethod(method);
// 设置不用缓存
conn.setUseCaches(false);
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
// 设置文件字符集:
conn.setRequestProperty("Charset", "UTF-8");
byte[] tmp = new byte[0];
if ("POST".equals(method) && data != null && data.length() > 0) {
//转换为字节数组
tmp = data.getBytes();
// 设置文件长度
conn.setRequestProperty("Content-Length", String.valueOf(tmp.length));
}
// 设置文件类型:
conn.setRequestProperty("contentType", "application/json");
conn.setRequestProperty("content-Type", "application/json");
/**设置URLConnection的参数和普通的请求属性****end***/
/**GET方法请求*****start*/
/**
* 如果只是发送GET方式请求,使用connet方法建立和远程资源之间的实际连接即可;
* 如果发送POST方式的请求,需要获取URLConnection实例对应的输出流来发送请求参数。
* */
conn.connect();
/**GET方法请求*****end*/
/***POST方法请求****start*/
if ("POST".equals(method) && data != null && data.length() > 0) {
//获取URLConnection对象对应的输出流
OutputStream out = conn.getOutputStream();
//发送请求参数即数据
out.write(tmp);
out.flush();
out.close();
}
/***POST方法请求****end*/
// 请求返回的状态
if (conn.getResponseCode() == 200) {
System.out.println("连接成功");
//获取URLConnection对象对应的输入流
InputStream is = conn.getInputStream();
//构造一个字符流缓存
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String str = "";
while ((str = br.readLine()) != null) {
//解决中文乱码问题
str = new String(str.getBytes(), "UTF-8");
sb.append(str);
System.out.println(str);
}
//关闭流
is.close();
}
//断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
//固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些。
conn.disconnect();
System.out.println("完整结束");
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
另外上传文件也可用这个,post改造一下
public static String doPostFile(String url, String filePath) {
// 获取到要上传的文件的输入流信息,通过ByteArrayOutputStream流转成byte[]
BufferedInputStream bis = null;
byte[] body_data = null;
try {
bis = new BufferedInputStream(new FileInputStream(filePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int c = 0;
byte[] buffer = new byte[8 * 1024];
try {
while ((c = bis.read(buffer)) != -1) {
baos.write(buffer, 0, c);
baos.flush();
}
body_data = baos.toByteArray();
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
// 将上传控件之外的其他控件的数据信息存入map对象
//Map<String, String> map = new HashMap<String, String>();
String fileName = filePath.substring(filePath.lastIndexOf(File.separatorChar) + 1);
//map.put("file",fileName);
URL urlObj = null;
HttpURLConnection httpConn = null;
BufferedReader reader = null;
try {
String BOUNDARY = UUID.randomUUID().toString().replace("-", "");
urlObj = new URL(url);
httpConn = (HttpURLConnection) urlObj.openConnection();
httpConn.setConnectTimeout(10000);
// 设置发起连接的等待时间,10s
httpConn.setReadTimeout(300000);
// 设置数据读取超时的时间,300s
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);
StringBuffer strBuf = new StringBuffer();
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"convertType\"").append("\r\n\r\n");
//转换类型
strBuf.append("类型");
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"isDelSr\"").append("\r\n\r\n");
//是否删除源文件:0=删除,1=不删除
strBuf.append("0");
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"\r\n");
strBuf.append("Content-Type: application/json\r\n\r\n");
bos.write(strBuf.toString().getBytes());
// 开始写出文件的二进制数据
bos.write(body_data);
bos.write(("\r\n--" + BOUNDARY).getBytes());
bos.flush();
bos.close();
os.close();
// 读取返回数据
StringBuffer strRet = new StringBuffer();
reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
strRet.append(line);
}
reader.close();
return fileName+": "+strRet.toString();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (reader != null) {
reader = null;
}
httpConn.disconnect();
}
return "-1";
}
如果是大型正规应用还是推荐
RestTemplate
|