大多数框架封装的都是java.net包中的HttpURLConnection类。
public void useGet(View view) {
new Thread(){
@Override
public void run() {
try {
get();
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
public void get()throws Exception{
String path = "http://www.baidu.com";
URL url= new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(60000);
connection.connect();
if(connection.getResponseCode() == 200){
InputStream inputStream = connection.getInputStream();
byte[]data = readStream(inputStream);
Log.i("wdd","get data is "+new String(data,"UTF-8"));
}else {
Log.i("wdd","get data failed ");
}
}
public void usePost(View view) {
new Thread(){
@Override
public void run() {
try {
post();
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
public void post()throws Exception {
String path = "http://www.baidu.com";
String params = "id=" + URLEncoder.encode("helloworld", "UTF-8")
+ "&pwd=" + URLEncoder.encode("android", "UTF-8");
byte[] postData = params.getBytes();
URL url = new URL(path);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(5*1000);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setInstanceFollowRedirects(true);
httpURLConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencode");
// Send parameter
DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
dos.write(postData);
dos.flush();
dos.close();
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == 200) {
// 获取返回的数据
byte[] data = readStream(httpURLConnection.getInputStream());
Log.i("wdd", "Post请求方式成功,返回数据如下:");
Log.i("wdd", new String(data, "UTF-8"));
} else {
Log.i("wdd", "Post方式请求失败");
}
}
public static byte[] readStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = inStream.read(buffer)) != -1) {
outSteam.write(buffer, 0, len);
}
outSteam.close();
inStream.close();
return outSteam.toByteArray();
}