/**
* get请求 (返回值为JSON)
* @return
* @throws IOException
* @throws IOException
*/
public static Map<String,Object> sendMethod(String requestUrl){
JSONObject json=new JSONObject();
try {
URL url = new URL(requestUrl);
HttpURLConnection connt = (HttpURLConnection)url.openConnection();
String strMessage=connt.getResponseMessage();
if(strMessage.compareTo("Not Found")!=0){
BufferedReader in = new BufferedReader(new InputStreamReader(connt.getInputStream(),"utf-8"));
String inputLine = null;
while ( (inputLine = in.readLine()) != null) {
json=JSONObject.parseObject(inputLine);
}
in.close();
}else{
json.put("Code", -1);
json.put("Message", "无法连接网络");
}
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
/**
* body提交方式
* post方法提交
* @param requestUrl
* @return
*/
public static JSONObject sendMethodPost(String requestUrl,Map<String, String> params){
JSONObject json=new JSONObject();
try {
URL url = new URL(requestUrl);// 创建连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod("POST"); // 设置请求方式
connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
connection.connect();
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
out.append(params.toString());
out.flush();
out.close();
int code = connection.getResponseCode();
InputStream is = null;
if (code == 200) {
is = connection.getInputStream();
} else {
is = connection.getErrorStream();
}
// 读取响应
int length = (int) connection.getContentLength();// 获取长度
if (length != -1) {
byte[] data = new byte[length];
byte[] temp = new byte[512];
int readLen = 0;
int destPos = 0;
while ((readLen = is.read(temp)) > 0) {
System.arraycopy(temp, 0, data, destPos, readLen);
destPos += readLen;
}
String result = new String(data, "UTF-8"); // utf-8编码
System.out.println("result:"+result);
}
} catch (IOException e) {
log.error("Exception occur when send http post request!", e);
}
return json; // 自定义错误信息
}
/**
* PUT方式提交
* @param dst_ip
*/
public static Map<String,Object> doPut(String strUrl,String param){
CloseableHttpClient httpclient = HttpClients.createDefault();
StringBuffer jsonString= new StringBuffer();
JSONObject json = new JSONObject();
try {
final HttpPut put=new HttpPut(strUrl);
put.setEntity(new StringEntity(param,"UTF-8"));
CloseableHttpResponse response1= httpclient.execute(put);
try {
HttpEntity entity1 = response1.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(entity1.getContent(),"utf-8"));
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
EntityUtils.consume(entity1);
} finally {
response1.close();
}
json=JSONObject.parseObject(jsonString.toString());
}catch(Exception e){
e.printStackTrace();
}
return json;
}
/**
* DELETE方式提交
* @param dst_ip
*/
public static String doDelete(String urlToRead) throws Exception {
URL url = new URL(urlToRead);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded" );
httpCon.setRequestMethod("DELETE");
httpCon.connect();
httpCon.disconnect();
// 获取返回的数据
BufferedReader in = new BufferedReader(new InputStreamReader(httpCon.getInputStream(),"utf-8"));
String line = null;
StringBuffer content = new StringBuffer();
while ((line = in.readLine()) != null) {
// line 为返回值,这就可以判断是否成功
content.append(line);
}
in.close();
return content.toString();
}
/**
* 函数功能描述:UTC时间转本地时间格式
* @param utcTime UTC时间
* @param utcTimePatten UTC时间格式
* @param localTimePatten 本地时间格式
* @return 本地时间格式的时间
* eg:utc2Local("2017-06-14 09:37:50.788+08:00", "yyyy-MM-dd HH:mm:ss.SSSXXX", "yyyy-MM-dd HH:mm:ss.SSS")
*/
public static String utc2Local(String utcTime, String utcTimePatten, String localTimePatten) {
SimpleDateFormat utcFormater = new SimpleDateFormat(utcTimePatten);
utcFormater.setTimeZone(TimeZone.getTimeZone("UTC"));//时区定义并进行时间获取
Date gpsUTCDate = null;
try {
gpsUTCDate = utcFormater.parse(utcTime);
} catch (Exception e) {
e.printStackTrace();
return utcTime;
}
SimpleDateFormat localFormater = new SimpleDateFormat(localTimePatten);
localFormater.setTimeZone(TimeZone.getDefault());
String localTime = localFormater.format(gpsUTCDate.getTime());
return localTime;
}
/**
* 表单提交方式
* @method: requestSend
* @param: [url, map]
* @date: 2019/4/29 17:33
* @return:
* @version: v1.0
*/
public static String requestSend(String url, Map<String,String> map) {
HttpResponse response = null;
HttpClient client = null;
HttpPost httpPost = new HttpPost(url);
try {
List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
for(String key : map.keySet()) {
list.add(new BasicNameValuePair(key,map.get(key).toString()));
}
UrlEncodedFormEntity uefe = new UrlEncodedFormEntity(list,"utf-8");
uefe.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(uefe);
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
client = HttpClients.createDefault();
response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
String res = EntityUtils.toString(entity, "utf-8");
return res;
}catch (Exception e) {
e.printStackTrace();
return null;
}finally {
httpPost.releaseConnection();
}
}
java中post delete get请求
最新推荐文章于 2023-07-12 21:48:24 发布