1、post请求
/**
* POST请求
*
* @param requestUrl 请求地址
* @param param 请求数据
* @return
*/
public static String post(String requestUrl, String param,String authtoken) {
HttpURLConnection connection = null;
InputStream is = null;
OutputStream os = null;
BufferedReader br = null;
String result = null;
try {
trustAllHosts();
/** 创建远程url连接对象 */
URL url = new URL(requestUrl);
/** 通过远程url对象打开一个连接,强制转换为HttpUrlConnection类型 */
connection = (HttpURLConnection) url.openConnection();
/** 设置连接方式:POST */
connection.setRequestMethod("POST");
/** 设置连接主机服务器超时时间:15000毫秒 */
connection.setConnectTimeout(15000);
/** 设置读取远程返回的数据时间:60000毫秒 */
connection.setReadTimeout(60000);
/** 设置是否向httpUrlConnection输出,设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个 */
// 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
connection.setDoOutput(true);
// 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
connection.setDoInput(true);
/** 设置通用的请求属性 */
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式
connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
connection.setRequestProperty("Auth-Token", authtoken);
/** 通过连接对象获取一个输出流 */
os = connection.getOutputStream();
/** 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的 */
// 若使用os.print(param);则需要释放缓存:os.flush();即使用字符流输出需要释放缓存,字节流则不需要
if (param != null && param.length() > 0) {
os.write(param.getBytes());
}
/** 请求成功:返回码为200 */
if (connection.getResponseCode() == 200) {
/** 通过连接对象获取一个输入流,向远程读取 */
is = connection.getInputStream();
/** 封装输入流is,并指定字符集 */
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
/** 存放数据 */
StringBuffer sbf = new StringBuffer();
String line = null;
while ((line = br.readLine()) != null) {
sbf.append(line);
sbf.append("\r\n");
}
result = sbf.toString();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
/** 关闭资源 */
try {
if (null != br) {
br.close();
}
if (null != is) {
is.close();
}
if (null != os) {
os.close();
}
} catch (Exception e) {
e.printStackTrace();
}
/** 关闭远程连接 */
// 断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
// 固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些
connection.disconnect();
System.out.println("--------->>> POST request end <<<----------");
}
return result;
}
2、put请求
/**
* put请求 上传文件
*
* @param requestUrl 请求地址
* @return
*/
public static int put(String requestUrl) {
InputStream is = null;
OutputStream os = null;
BufferedReader br = null;
String result = null;
int responseCode = 0;
try {
File file = new File("测试.pdf");
URL apiUrl = new URL(requestUrl);
// 创建一个信任所有证书的 TrustManager
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
connection.setRequestMethod("PUT");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/octet-stream");
try (FileInputStream fileInputStream = new FileInputStream(file);
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
}
responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 上传成功
System.out.println("File uploaded successfully");
} else {
// 上传失败
System.out.println("File upload failed with response code: " + responseCode);
}
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return responseCode;
}
文章来源地址https://www.toymoban.com/news/detail-506121.html
文章来源:https://www.toymoban.com/news/detail-506121.html
到了这里,关于Java http 接口请求的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!