安卓APP请求URL的四种方式
直接请求:GET方式
/**
* 发送GET请求
* @param path 请求路径
* @param params 请求参数
* @return 请求是否成功
* @throws Exception
*/
private static boolean sendGETRequest(String path,
Map<String, String> params, String ecoding) throws Exception {
StringBuilder url = new StringBuilder(path);
url.append("?");
for(Map.Entry<String, String> entry:params.entrySet()){
url.append(entry.getKey()).append("=");
url.append(URLEncoder.encode(entry.getValue(), ecoding));
url.append("&");
}
url.deleteCharAt(url.length()-1);
HttpURLConnection conn = (HttpURLConnection) new URL(url.toString()).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if(conn.getResponseCode() == 200){
return true;
}
return false;
}
直接请求:POST方式
/**
* 发送Post请求
* @param path 请求路径
* @param params 请求参数
* @param encoding 编码
* @return 请求是否成功
*/
private static boolean sendPOSTRequest(String path, Map<String, String> params, String encoding) throws Exception{
// title=liming&timelength=90
StringBuilder data = new StringBuilder();
if(params!=null && !params.isEmpty()){
for(Map.Entry<String, String> entry : params.entrySet()){
data.append(entry.getKey()).append("=");
data.append(URLEncoder.encode(entry.getValue(), encoding));
data.append("&");
}
data.deleteCharAt(data.length() - 1);
}
byte[] entity = data.toString().getBytes();//生成实体数据
HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("POST");
conn.setDoOutput(true);//允许对外输出数据
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(entity.length));
OutputStream outStream = conn.getOutputStream();
outStream.write(entity);
if(conn.getResponseCode() == 200){
return true;
}
return false;
}
模拟一个客户端(浏览器)请求方式:返回的流数据相当于浏览器解析后的数据:GET方式
public String doGetOfHttpClient(String userName,String password){
//1.模拟一个客户端(浏览器)
HttpClient client = new DefaultHttpClient();
//2.创建一个get请求方法
String data = "?username=" + URLEncoder.encode(userName) + "&password=" + URLEncoder.encode(password);
HttpGet get = new HttpGet("http://172.21.13.1/sysmap/login.php"+data);
//设置请求时间
HttpParams params = get.getParams();//得到默认的参数,在此基础上追加超时时间设置
//设置连接服务器的超时时间
HttpConnectionParams.setConnectionTimeout(params, 1000*10);
//读取数据的超时时间
HttpConnectionParams.setSoTimeout(params, 1000*10);
System.out.println("开始");
try {
//3.使用客户端执行get方法,获得服务器响应对象
System.out.println("开始2");
HttpResponse response = client.execute(get);
System.out.println("开始3");
StatusLine statusLine = response.getStatusLine(); //获取系统的状态栏
System.out.println("开始4");
int statusCode = statusLine.getStatusCode(); //在状态栏中获取状态码
System.out.println("状态码:"+statusCode);
if(statusCode == 200){
//4.获得服务端返回的数据
HttpEntity entity = response.getEntity(); //获取服务端返回的实体(数据)
return EntityUtils.toString(entity, "utf-8"); //使用实体工具类获得字符串
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
System.out.println("ClientProtocolException"+e.toString());
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("IOException"+e.toString());
e.printStackTrace();
}finally{
if(client != null){
client.getConnectionManager().shutdown(); //关闭连接
}
}
return null;
}
public String doPostOfHttpClient(String username,String password){
//1.模拟一个客户端(浏览器)
HttpClient client = new DefaultHttpClient();
//2.创建一个post请求方法
HttpPost post = new HttpPost("http://172.21.13.1/sysmap/login.php");
//设置请求时间
HttpParams params = post.getParams();//得到默认的参数,在此基础上追加超时时间设置
//设置连接服务器的超时时间
HttpConnectionParams.setConnectionTimeout(params, 1000*10);
//读取数据的超时时间
HttpConnectionParams.setSoTimeout(params, 1000*10);
System.out.println("开始");
try {
//需要把数据添加到post方法中。
List<NameValuePair> entity = new ArrayList<NameValuePair>();
entity.add(new BasicNameValuePair("username", username));
entity.add(new BasicNameValuePair("password", password));
post.setEntity(new UrlEncodedFormEntity(entity, "utf-8"));
//3.使用客户端执行post方法,获得服务器响应对象
System.out.println("开始2");
HttpResponse response = client.execute(post);
System.out.println("开始3");
int statusCode = response.getStatusLine().getStatusCode(); //在状态栏中获取状态码
System.out.println("状态码:"+statusCode);
if(statusCode == 200){
//4.获得服务端返回的数据
HttpEntity httpEntity = response.getEntity(); //获取服务端返回的实体(数据)
return EntityUtils.toString(httpEntity, "utf-8"); //使用实体工具类获得字符串
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
System.out.println("ClientProtocolException"+e.toString());
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("IOException"+e.toString());
e.printStackTrace();
}finally{
if(client != null){
client.getConnectionManager().shutdown(); //关闭连接
}
}
return null;
}