7 回答

TA贡献1821条经验 获得超4个赞
可以指定请求方式: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;
}
添加回答
举报