方法一
1.现将要传输的参数转化为json格式
比如将对象转为json格式:JSONObject jsonObj = JSONObject.fromObject(data);
2.拼装url
String url = "******url?data="+jsonObj
3.调用以下方法
public String loadJSON(String url) {
StringBuilder json = new StringBuilder();
try {
URL oracle = new URL(url);
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine = null;
while ((inputLine = in.readLine()) != null) {
json.append(inputLine);
}
in.close();
} catch (IOException e) {
}
return json.toString();
}
接受参数是String类型
方法二:
1.将参数转换成json格式
2.拼装url,不带参数
3.调用下面方法
public String send(String url, Resources res) {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
headers.setContentType(type);
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
JSONObject jsonObj = JSONObject.fromObject(res);
String result = restTemplate.postForObject(url, jsonObj.toString(), String.class);
return result;
}
方法三:
1.将参数转换成json格式
2.拼装url,不带参数
3.调用下面方法
public void sendPost(String urls, String param) {
try {
URL url = new URL(urls);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "text/plain;charset=utf-8");
connection.connect();
// POST请求
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
//参数
out.writeBytes("data=" + param);
System.out.println("data=" + param);
out.flush();
out.close();
// 读取响应
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String lines;
StringBuffer sb = new StringBuffer("");
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
sb.append(lines);
}
System.out.println(sb);
reader.close();
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}