GET请求
public static String requestByGet(Context context,String path) throws Exception{
String data = "";
// 新建一个URL对象
URL url = new URL(path);
// 打开一个HttpURLConnection连接
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
// 设置连接超时时间
urlConn.setConnectTimeout(3 * 1000);
// 开始连接
urlConn.connect();
// 判断请求是否成功
if (urlConn.getResponseCode() == 200) {
// 获取返回的数据
data = IOUtils.getTextFromStream(urlConn.getInputStream());
} else {
ToastUtil.showShort(context,"请求失败");
}
// 关闭连接
urlConn.disconnect();
return data;
}
POST请求
public static String requestByPost(Context context,String path)throws Exception{
String data = "";
String params = "name="+ URLEncoder.encode("username", "UTF-8")
+ "&password=" + URLEncoder.encode("password", "UTF-8");
byte[] postData = params.getBytes();
// 新建一个URL对象
URL url = new URL(path);
// 打开一个HttpURLConnection连接
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
// 设置连接超时时间
urlConn.setConnectTimeout(3 * 1000);
// Post请求必须设置允许输出
urlConn.setDoOutput(true);
// Post请求不能使用缓存
urlConn.setUseCaches(false);
// 设置为Post请求
urlConn.setRequestMethod("POST");
urlConn.setInstanceFollowRedirects(true);
// 配置请求Content-Type
urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencode");
// 开始连接
urlConn.connect();
// 发送请求参数
DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());
dos.write(postData);
dos.flush();
dos.close();
// 判断请求是否成功
if (urlConn.getResponseCode() == 200) {
// 获取返回的数据
data = IOUtils.getTextFromStream(urlConn.getInputStream());
} else {
ToastUtil.showShort(context,"请求失败");
}
return data;
}
其中的ToastUtil是一个Toast的自定义基类:
public class ToastUtil {
public static void showShort(Context context,String content){
Toast.makeText(context, content, Toast.LENGTH_SHORT).show();
}
public static void showLong(Context context,String content){
Toast.makeText(context, content, Toast.LENGTH_LONG).show();
}
public static void showShort(Context context,int contentId){
Toast.makeText(context, contentId, Toast.LENGTH_SHORT).show();
}
public static void showLong(Context context,int contentId){
Toast.makeText(context, contentId, Toast.LENGTH_LONG).show();
}
}
IOutils为解析InputStream的一个工具类:
public class IOUtils {
public static String getTextFromStream(InputStream inputStream){
byte[] b = new byte[1024];
int len = 0;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
while ((len = inputStream.read(b))!=-1){
byteArrayOutputStream.write(b,0,len);
}
String text = new String(byteArrayOutputStream.toByteArray());
return text;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}