1.application/x-www-form-urlencoded 接口中这种参数类型是以键值对发送给后台解析例如;key1=value1&key2=value2,该示例中通过获取map键值对拼接,如下:
public static String wdtPost(String uri, Map<String, String> params) {
String response = "";
try {
URL url = new URL(uri);
// 开始访问
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, String> param : params.entrySet()) {
if (postData.length() != 0)
postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(
String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=utf-8");
conn.setRequestProperty("Content-Length",
String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
Reader in = new BufferedReader(new InputStreamReader(
conn.getInputStream(), "UTF-8"));
StringBuilder sb = new StringBuilder();
for (int c; (c = in.read()) >= 0;)
sb.append((char) c);
response = sb.toString();
// System.out.println(response);
} catch (Exception e) {
// TODO: handle exception
}
return response;
}
2.application/json 接口中这种参数类型是比较简单也比较常见的JSON串类型,可以下载一个fastjson的jar包把集合转化成json,比较方便和简单,如下:
public static String request(String apiUrl, String method, String paramsStr) {
try {
URL url = new URL(apiUrl);// 创建连接
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod(method); // 设置请求方式
if (method.toLowerCase().equals("post")) {
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type",
"application/json");
}
connection.connect();
OutputStreamWriter out = new OutputStreamWriter(
connection.getOutputStream(), "UTF-8");
out.append(paramsStr);
out.flush();
out.close();
int code = connection.getResponseCode();
if (code != 200) {
// 错误处理
return connection.getResponseMessage();
}
// 接收返回信息
InputStreamReader in = new InputStreamReader(
connection.getInputStream(), "UTF-8");
StringBuffer response = new StringBuffer();
final char[] buff = new char[1024];
int read = 0;
while ((read = in.read(buff)) > 0)
response.append(buff, 0, read);
return response.toString();
} catch (IOException e) {
// 自定义错误信息
return e.getMessage();
}
}
3.multipart/form-data 接口中这种参数类型是指定传输数据为二进制数据,例如图片、mp3、文件 如下:
public static String sendFile(String url, String param,
BufferedInputStream bInputStream) {
BufferedOutputStream out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("contentType", "multipart/form-data");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 发送参数
StringBuffer sb = new StringBuffer();
sb = sb.append(param);
byte[] paramData = sb.toString().getBytes();
// System.out.println(paramData.length);
out = new BufferedOutputStream(conn.getOutputStream());
out.write(paramData);
if (bInputStream != null) {
byte[] data = new byte[2048];
while (bInputStream.read(data) != -1) {
out.write(data);
}
}
out.flush();
// flush输出流的缓冲
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
// System.out.println("发送 POST 请求出现异常!" + e);
result = new StringBuilder(
"{\"resCode\":\"1\",\"errCode\":\"1001\",\"resData\":\"\"}");
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
if (bInputStream != null) {
bInputStream.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result.toString();
}
4.text/plain:纯文本的传输。空格转换为“+”,但不支持特殊字符编码