android 发送http请求 百度网页

来源:互联网 发布:linux中rpm文件 编辑:程序博客网 时间:2024/06/15 18:26

package com.example.net;



import java.io.IOException;
import java.io.InputStream;


import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;


import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;


public class MainActivity extends Activity {


Button bn_get;



@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


bn_get = (Button) findViewById(R.id.get);
bn_get.setOnClickListener(new OnClickListener() {


@Override
public void onClick(View v) {
// TODO Auto-generated method stub
get();
}
});
}


public void get()
{
MyThread myThread1 = new MyThread(); 
myThread1.start();
}

public class MyThread extends Thread {  
public void run() {

try {
HttpClient client = new DefaultHttpClient();
String urlString = "http://www.baidu.com";
HttpGet get = new HttpGet(urlString);
HttpResponse response = client.execute(get);
InputStream inputStream = response.getEntity().getContent();
byte[] data =StreamUtils.readInputStream(inputStream);
String resultString = new String(data,"utf-8");
Log.i("ztt",resultString);
inputStream.close();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}  


}


}




工具类  StreamUtils 


package com.example.net;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;


public class StreamUtils {


public static String readStream(InputStream is) {
try {
byte[] bytes = readInputStream(is);
return new String(bytes);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}


public static byte[] readInputStream(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
is.close();
return baos.toByteArray();
}
}

0 0
原创粉丝点击