首先,贴一段请求的完整代码
public static String httpDomain(String urlStr, Map<String, String> params) {
URL connect;
OutputStreamWriter paramout = null;
BufferedReader reader = null;
StringBuffer data = new StringBuffer();
try {
connect = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection)connect.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);// post不能使用缓存
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
// 转换请求所需参数格式
String paramsStr = JSONObject.toJSONString(params);
paramout = new OutputStreamWriter(connection.getOutputStream(), "utf-8");
paramout.write(paramsStr);
paramout.flush();
// 获取URLConnection对象对应的输入流
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
String line = "";
while ((line = reader.readLine()) != null) {
data.append(line);
}
is.close();
} catch (Exception e) {
String msg = "异常消息";
log.error(msg, e);
} finally {
try {
if (null != paramout) {
paramout.close();
}
if (null != reader) {
reader.close();
}
} catch (IOException e) {
String msg = "流关闭错误";
log.error(msg, e);
}
}
return data.toString();
}
需要特别注意的是,如果服务器需要的是JSON格式的参数,那无论客户端是什么类型的参数,都需要通过以下方式转换为JSON格式的字符串,要么调用时很可能返回400错误,切记!
// 转换请求所需参数格式
String paramsStr = JSONObject.toJSONString(params);