Android开发-02-自己常用的一个get和post方式提交类的封装

来源:互联网 发布:知乎wifi刷不出来图片 编辑:程序博客网 时间:2024/06/18 15:10
package com.zhimei.footbath.utils;


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;


import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;


public class NetWorkUtil {
/**
* 发送post请求

* @param url
* @param params
* @return
*/
public static String doPost(String url, Map<String, String> params) {
List<NameValuePair> pairList = new ArrayList<NameValuePair>();
NameValuePair pair = null;
Iterator<Entry<String, String>> iterator = params.entrySet()
.iterator();
while (iterator.hasNext()) {// 只遍历一次,速度快
Entry<String, String> entry = iterator.next();
String key = entry.getKey().toString();
String value = entry.getValue().toString();
pair = new BasicNameValuePair(key, value);
pairList.add(pair);
}
try {
HttpEntity requestHttpEntity = new UrlEncodedFormEntity(
pairList, HTTP.UTF_8);
// URL使用基本URL即可,其中不需要加参数
HttpPost httpPost = new HttpPost(url);
// 将请求体内容加入请求中
httpPost.setEntity(requestHttpEntity);
// 需要客户端对象来发送请求
HttpClient httpClient = new DefaultHttpClient();
// 发送请求
HttpResponse response = httpClient.execute(httpPost);
// 显示响应
String result = getResponseResult(response);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}


/**
* 发送get请求

* @param baseUrl
* @param params
* @return
*/
public static String doGet(String baseUrl, Map<String, String> params) {
String url = baseUrl;
if (params != null && params.size() > 0) {
Iterator<Entry<String, String>> iterator = params
.entrySet().iterator();
while (iterator.hasNext()) {// 只遍历一次,速度快
Entry<String, String> entry = iterator.next();
String key = entry.getKey().toString();
String value = entry.getValue().toString();
url = url + "?" + key + "=" + value + "&";
}
// 去掉最后一个&符号
url = url.substring(0, url.length() - 1);
// 去掉中间添加的多余?符号
url = url.replace("&?", "&");
}
// 生成请求对象
HttpGet httpGet = new HttpGet(url);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse;
try {
httpResponse = httpClient.execute(httpGet);
String result = getResponseResult(httpResponse);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;


}


/**
* post方式提交,以流的的方式提交

* @param jsonParam
* @return
*/
public static String doPost2(String urlPath, String jsonParam) {
URL url;
try {
url = new URL(urlPath);
String content = String.valueOf(jsonParam);
// 现在呢我们已经封装好了数据,接着把封装好的数据传递过去
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setConnectTimeout(5000);
// 设置允许输出
conn.setDoOutput(true);
conn.setRequestMethod("POST");
// 设置User-Agent: Fiddler
conn.setRequestProperty("ser-Agent", "Fiddler");
// 设置contentType
conn.setRequestProperty("Content-Type",
"application/json");
OutputStream os = conn.getOutputStream();
os.write(content.getBytes());
os.close();


return conn.getResponseCode() + ":"
+ conn.getResponseMessage();


} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;


}


/**
* 获取http请求返回的结果

* @param response
*/
public static String getResponseResult(HttpResponse response) {
if (null == response) {
return null;
}
int code = response.getStatusLine().getStatusCode();
HttpEntity httpEntity = response.getEntity();
try {
InputStream inputStream = httpEntity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String result = "";
String line = "";
while (null != (line = reader.readLine())) {
result += line;
}
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;


}


public static boolean isNetworkAvailable(Context context) {
ConnectivityManager mgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] info = mgr.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
return false;
}


}
1 0
原创粉丝点击