可以指定请求方式:connection.setRequestMethod("POST");如下代码
public static String httpPostWithJson(String ecUrl, String params) {
BufferedReader reader = null;
HttpURLConnection connection = null;
try {
URL url = new URL(ecUrl);
connection = (HttpURLConnection) url.openConnection();
// 创建连接
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.connect();
// POST请求
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(params);
out.flush();
out.close();
// 读取响应
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);
}
return sb.toString();
} catch (MalformedURLException e) {
logger.error("httpPostWithJsonMalformedURLException error", e);
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
logger.error("httpPostWithJsonUnsupportedEncodingException error", e);
e.printStackTrace();
} catch (IOException e) {
logger.error("httpPostWithJsonIOException error", e);
e.printStackTrace();
} finally {
try {
if (null != reader) {
reader.close();
}
if (null != connection) {
connection.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
这是用的spring mvc?
没有指明RequestMethod方法,则符合RequestMapping规则的get,Post都可以.不过从方法名来看,这里应该是使用get方法比较好.
特例是
如果存在同规则RequestMapping的话,同名RequestMapping指明了单个RequestMethod方法,则它的优先级会高
4 回答1.2k 阅读✓ 已解决
4 回答1.2k 阅读✓ 已解决
1 回答2.5k 阅读✓ 已解决
2 回答715 阅读✓ 已解决
2 回答1.7k 阅读
2 回答1.7k 阅读
2 回答1.3k 阅读
以上代码没有指定请求必须是GET方法还是PUT/POST或其他方法,@RequestMapping注解默认会映射所有的HTTP请求方法。如果仅想接收某种请求方法,请在注解中指定之@RequestMapping(method=GET)以缩小范围。
这是Spring MVC中关于@RequestMapping的说明文档,多看文档大兄弟。