需要注意的是:
安卓下需要引入httpmime.jar 点击打开链接
HttpPost httppost = new HttpPost(url);
MultipartEntity reqEntity = new MultipartEntity();
//此处为文件上传
if (files != null && files.size() > 0) {
for (Map.Entry<String, String> en : files.entrySet()) {
reqEntity.addPart(en.getKey(), new FileBody(new File(en.getValue())));//file1为请求后台的File upload;属性
}
}
//此处为参数上传
if (map != null && map.size() > 0) {
for (Map.Entry<String, String> en : map.entrySet()) {
reqEntity.addPart(en.getKey(), new StringBody(en.getValue()));
}
}
//设置请求头信息
httppost.setHeader("User-Agent", WeiTaiXinApplication.instance.getUser_agent());
httppost.setEntity(reqEntity);
// 3: 获取默认的请求client
DefaultHttpClient client = new DefaultHttpClient();
// 4.1:设置请求超时
client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_CONNECTION_OUT);
// 4.2:设置读取超时
client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, TIME_SO_OUT);
// 4.3:设置HttpClient会在请求中携带由服务器返回的Cookie
client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);
// 5:取得HTTP Response
HttpResponse response = client.execute(httppost);
/** 6.服务器返回状态吗 **/
int statusCode = response.getStatusLine().getStatusCode();
LogUtils.i("服务器响应状态码:" + statusCode);
// 状态码为200代表OK
if (statusCode == 200) {
/** 服务器返回数据 **/
String strResult = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
}