java 调用第三方url接口
1、GET请求
/**
* address
* param 参数
* get请求
*/
public static String get(String address,String param ){
HttpURLConnection connection = getConnection(address);
try {
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("param ", param );
} catch (ProtocolException e) {
e.printStackTrace();
}
return access(connection);
}
2、POST请求
```bash
/**
* post请求
* address 地址
* param 参数
* token
*/
public static String post(String address,String param,String token){
HttpURLConnection connection = getConnection(address);
try {
connection.setRequestMethod("POST");
connection.setDoOutput(true);
// 设置维持长连接
connection.setRequestProperty("Connection", "Keep-Alive");
// COOKIE
connection.setRequestProperty("Cookie", "aaa=bbb;ccc=ddd;fid=789");
if(StringUtils.isNotEmpty(token)){
connection.setRequestProperty("token", token);
}
// USER-AGENT
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36");
connection.setRequestProperty("Content-Type","application/json;charset=utf-8");
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.write(param.getBytes(StandardCharsets.UTF_8));
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
return access(connection);
}
/**
* 访问网络
*/
private static String access(HttpURLConnection connection){
StringBuilder result = new StringBuilder();
try {
connection.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
reader.close();
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return result.toString();
}
调用
```java
public static void main(String[] args) {
String appid = "XXX";
String key = "XXX";
String url = "XXX";
JSONObject jsonObject = new JSONObject();
jsonObject.put("appid", appid);
jsonObject.put("key", key);
String data = NetUtil.post(url,jsonObject.toJSONString(),"");
JSONObject obj = JSONObject.parseObject(data);
String token ="";
if(obj!=null){
JSONObject json = obj.getJSONObject("data");
token = json.getString("token");
}
System.out.println(token);
}