1.用android自带的api实现http的get请求
public void get(final Handler handler, final String webUrl){
//用android自带的api实现http请求
new Thread(){
@Override
public void run() {
try {
URL url=new URL(webUrl);
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(60000);
connection.setReadTimeout(60000);
connection.setDoInput(true);
connection.setDoOutput(true);
InputStream inputStream=connection.getInputStream();
byte[] data=new byte[1024];
int count=0;
StringBuffer stringBuffer=new StringBuffer();
while ((count=inputStream.read(data))>0){
stringBuffer.append(new String(data,0,count));
}
Message message=handler.obtainMessage();
Bundle bundle=new Bundle();
bundle.putString("data",stringBuffer.toString());
message.setData(bundle);
handler.sendMessage(message);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Bundle bundle=msg.getData();
String data=bundle.getString("data");
Log.d(TAG, data);
}
};
2.使用AsycHttpClient
AsyncHttpClient client=new AsyncHttpClient();
client.get(url, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int i, org.apache.http.Header[] headers, byte[] bytes) {
Log.d(TAG,"get:"+ new String(bytes));
}
@Override
public void onFailure(int i, org.apache.http.Header[] headers, byte[] bytes, Throwable throwable) {
Log.d(TAG,"failure");
}
});
RequestParams params=new RequestParams();
params.add("username","gst");
params.add("pwd","123");
client.post(url, params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int i, Header[] headers, byte[] bytes) {
Log.d(TAG,"post:"+ new String(bytes));
}
@Override
public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
Log.d(TAG,"failure");
}
});