您的位置:首页 > 移动开发 > Android开发

Android向服务器传送和接收数据的方法汇总

2014-04-06 10:05 387 查看
今天通过收集资料和自己尝试的使用,整理了Android向服务器发送数据的方法主要有以下几种,下面写在一个类中,相应的调用就可实现!

注意:开始我在使用时,调用各种方法总是报错,后来到处查找,但是就是找不到错误,最终在高手的指点下找到了原因,在网络编程时,调用各种方法时,我们一定要在线程完成。

源码:

package com.example.shezhi;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class Update
{
String res=" ";
int ites;
String version="1";

/////////////////////////////////////////////////////////////////////////////////////////
public String getupdate(){
//先将参数放入List,再对参数进行URL编码
List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
params.add(new BasicNameValuePair("param1", "1"));
params.add(new BasicNameValuePair("param2", "value2"));

//对参数编码
String param = URLEncodedUtils.format(params, "UTF-8");
//baseUrl
String baseUrl = "http://******/index1.jsp";
//将URL与参数拼接
HttpGet getMethod = new HttpGet(baseUrl + "?" + param);

HttpClient httpClient = new DefaultHttpClient();
try {
HttpResponse response = httpClient.execute(getMethod);
res="已经请求";
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //发起GET请求

try {
HttpResponse response = httpClient.execute(getMethod); //发起GET请求

ites=response.getStatusLine().getStatusCode(); //获取响应码
System.out.println(ites+"aaa");
res="1213"+EntityUtils.toString(response.getEntity(), "utf-8");//获取服务器响应内容
System.out.println(res+"vvv");

} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return res;
}

/********************************************************************************************
/**
* HttpClient  Post方法
* @return
*/
public String Postupdate(){
String urlPath="http://******/index1.jsp";
String realPath=urlPath.replaceAll(" ", "");//把多余的空格替换掉
HttpPost httpRequest=new HttpPost(realPath);
// 添加要传递的参数
List<NameValuePair> params = new ArrayList<NameValuePair>();
NameValuePair pair1 = new BasicNameValuePair("username", "gzw");
NameValuePair pair2 = new BasicNameValuePair("password", "123");
params.add(pair1);
params.add(pair2);
try
{
// 设置字符集
HttpEntity httpentity = new UrlEncodedFormEntity(params, "utf-8");
// 请求httpRequest
httpRequest.setEntity(httpentity);
// 取得默认的HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 取得HttpResponse
HttpResponse httpResponse = httpclient.execute(httpRequest);
// HttpStatus.SC_OK表示连接成功
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
// 取得返回的字符串
String strResult = EntityUtils.toString(httpResponse.getEntity());
res=strResult;
}
else
{

res="失败";
}

}catch  (Exception e)
{
e.printStackTrace();
}
return res;

}
/********************************************************************************************/
/**
* 调用java类  get方法
*/

public String get_update(){
String urlPath="http://******/index1.jsp"+"?type=save&version="+version+"";
String realPath=urlPath.replaceAll(" ", "");//把多余的空格替换掉
try
{
if(getRequest(realPath))
{
//成功
res="成功";
}

}catch  (Exception e)
{
res="失败";
}
return res;

}

/**
* java类  get方法
* @return
*/

//get请求,有文件长度大小限制
public static boolean getRequest(String urlPath) throws Exception
{
URL url=new URL(urlPath);
HttpURLConnection con=(HttpURLConnection)url.openConnection();
con.setRequestMethod("GET");
con.setReadTimeout(5*1000);
if(con.getResponseCode()==200)
{
return true;
}
return false;
}

/********************************************************************************************
/**
* 调用下面java类  Post方法
* @return
*/

public String post_update(){
String urlPath="http://www.gdhdcy.com/hdleague1/index1.jsp";
Map<String,String> map=new HashMap<String,String>();//用集合来做,比字符串拼接来得直观
map.put("type", "save");
map.put("version", version);
try
{
if(postRequest(urlPath,map))
{
//成功
res="成功";
}

}catch  (Exception e)
{
res="失败";
}
return res;

}
/**
* java类  post方法
* @return
*/
//post请求,无文件长度大小限制
public static boolean postRequest(String urlPath,Map<String,String> map) throws Exception
{
StringBuilder builder=new StringBuilder(); //拼接字符
//拿出键值
if(map!=null && !map.isEmpty())
{
for(Map.Entry<String, String> param:map.entrySet())
{
builder.append(param.getKey()).append('=').append(URLEncoder.encode(param.getValue(), "utf-8")).append('&');
}
builder.deleteCharAt(builder.length()-1);
}
//下面的Content-Length: 是这个URL的二进制数据长度
byte b[]=builder.toString().getBytes();
URL url=new URL(urlPath);
HttpURLConnection con=(HttpURLConnection)url.openConnection();
con.setRequestMethod("POST");
con.setReadTimeout(5*1000);
con.setDoOutput(true);//打开向外输出
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//内容类型
con.setRequestProperty("Content-Length",String.valueOf(b.length));//长度
OutputStream outStream=con.getOutputStream();
outStream.write(b);//写入数据
outStream.flush();//刷新内存
outStream.close();
//状态码是不成功
if(con.getResponseCode()==200)
{
return true;
}
return false;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: