网络请求连接代码如下:
public static String openUrl(String url, RequestParameter parameter) throws Exception {
URL urls = new URL(url);
HttpURLConnection connection = null;
OutputStream outputStream = null;
String rs = null;
try {
connection = (HttpURLConnection) urls.openConnection();
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=----footfoodapplicationrequestnetwork");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
connection.setRequestProperty("Accept", "*/*");
connection.setRequestProperty("Range", "bytes="+"");
connection.setConnectTimeout(8000);
connection.setReadTimeout(20000);
connection.setRequestMethod("POST");
StringBuffer buffer = new StringBuffer();
int len = 0;
if(parameter != null)
len = parameter.size();
for(int i = 0; i < len; i++) {
buffer.append("------footfoodapplicationrequestnetwork\r\n");
buffer.append("Content-Disposition: form-data; name=\"");
buffer.append(parameter.getKey(i));
buffer.append("\"\r\n\r\n");
buffer.append(parameter.getValue(i));
buffer.append("\r\n");
}
if(parameter != null)
buffer.append("------footfoodapplicationrequestnetwork--\r\n");
outputStream = connection.getOutputStream();
outputStream.write(buffer.toString().getBytes());
try {
connection.connect();
if(connection.getResponseCode() == 200) {
rs = getWebSource(connection.getInputStream());
}
}
catch (Exception e) {
rs = null;
}
return rs;
}
finally {
try {
outputStream.close();
}
catch (Exception e) {
}
outputStream = null;
if(connection != null)
connection.disconnect();
connection = null;
}
}
提交参数有一下注意:
1、Content-Type参数必须写明。格式为:multipart/form-data; boundary=----footfoodapplicationrequestnetwork,前面四条短线后面自定义字符串,只要不与其他字符串冲突就行。
2、form-data参数格式。
buffer.append("------footfoodapplicationrequestnetwork\r\n");
buffer.append("Content-Disposition: form-data; name=\"");
buffer.append(parameter.getKey(i));
buffer.append("\"\r\n\r\n");
buffer.append(parameter.getValue(i));
buffer.append("\r\n");
参数说明:
第一行为form-data的请求头,也就是boundary前面再加两个短线,貌似必须要加上\r\n。
第二行为form-data的参数名。
3、form-data结束标志。格式为:------footfoodapplicationrequestnetwork--\r\n
在boundary前加两个短线,在后加两个短线和\r\n。