您的位置:首页 > 理论基础 > 计算机网络

Android 通过http访问服务器

2013-07-21 18:35 429 查看
目前Android 与服务器交互有两种方式:1.Socket 2. Http ;

但由于Http的封装性以及性能比socket要好,所以推荐使用http方式和服务器交互;

通过http访问服务器有三种方法:1.post 2. get 3.或者上传文件

例子如下:

protected JSONObject toWebService(String url, String method,
List<NameValuePair> params) {
try {
Log.w("HealthCareAPI", "toWebService: url = " + url);
HttpUriRequest request = null;
if (HealthCareApi.GET_METHOD.equalsIgnoreCase(method)) {  //Get方法
url = url + "?" + URLEncodedUtils.format(params, "UTF-8");
Log.w("HealthCareApiCore", url);
request = new HttpGet(url);
} else if (HealthCareApi.POST_METHOD.equalsIgnoreCase(method)) {  //Post方法
HttpPost postRequest = new HttpPost(url);
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
params, HTTP.UTF_8);
postRequest.setHeader("Content-Type",
"application/x-www-form-urlencoded; charset=utf-8");
postRequest.setEntity(entity);
request = postRequest;
} else if (HealthCareApi.POST_METHOD_WITH_BIN
.equalsIgnoreCase(method)) {   //上传文件,这里指的是上传图片文件
HttpPost postRequest = new HttpPost(url);
MultipartEntity multipartContent = new MultipartEntity();
for (NameValuePair nameValuePair : params) {
if (nameValuePair.getName().equals("photo")
|| nameValuePair.getName().equals("pic")
|| nameValuePair.getName().equals("photo_url")) {
File photoFile = new File(nameValuePair.getValue());
if (photoFile.exists()) {
String extensionName = HealthCareApi
.getExtensionName(photoFile.getName());
FileBody fileBody = new FileBody(photoFile,
MimeTypeMap.getSingleton()
.getMimeTypeFromExtension(
new String(extensionName).toLowerCase()));
multipartContent.addPart(
nameValuePair.getName(), fileBody);
}
} else {
multipartContent.addPart(nameValuePair.getName(),
new StringBody(nameValuePair.getValue(),
Charset.forName("UTF-8")));
}
}
postRequest.setEntity(multipartContent);
request = postRequest;
}
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams
.setConnectionTimeout(httpParams, 20 * 1000);
HttpConnectionParams.setSoTimeout(httpParams, 20 * 1000);
HttpResponse httpResponse = new DefaultHttpClient(httpParams)
.execute(request);
HttpEntity entity = httpResponse.getEntity();
String res = EntityUtils.toString(entity, "UTF-8");
Log.w("HealtCareApi", "res: " + res);
JSONObject object = new JSONObject(res);
return object;
} catch (Exception e) {
e.printStackTrace();
mException = e;
}
return null;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: