前言
欢迎大家我分享和推荐好用的代码段~~
声明
欢迎转载,但请保留文章原始出处:
CSDN:http://www.csdn.net
雨季o莫忧离:http://blog.csdn.net/luckkof
正文
Http通信中使用的最多的是Get和Post。Get请求可以获取静态页面,也可以把参数放在url字符串后面传递给服务器。Post与Get的不同之处在于Post的参数不是放在url字符串里面,而是放在http请求数据中。HttpURLConnection是Java的标准类,继承自URLConnection类,URLConnection与 HttpURLConnection都是抽象类,去、、无法直接实例化对象。其对象主要通过URL的openConnection方法获得。下面就两种方式分别提供示例:
其中有两个资源文件,两个jsp的内容分别如下:
http.jsp
- <html>
- <head>
- <title>My JSP 'index.jsp' starting page</title>
- </head>
- <body>
- <%
- out.println("<h1>HTTP TEST<br/>http test</h1>");
- %>
- </body>
- </html>
- <html>
- <head>
- <title>My JSP 'index.jsp' starting page</title>
- </head>
- <body>
- <%
- String type = request.getParameter("par");
- String result = new String(type.getBytes("iso-8859-1"),"gb2312");
- out.println("<h1>parameters:"+result+"</h1>");
- %>
- </body>
- </html>
1、 HttpURLConnection 类通过Get方式获取网络资源:
- public class GetActivity extends Activity {
- private String TAG = "GetActivity";
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.http);
- TextView textView = (TextView)findViewById(R.id.text);
- String urlString = "http://127.0.0.1:8080/test/httpGet.jsp?par=test";//http地址
- String resultData = "";//获得的数据
- URL url = null;
- try {
- url = new URL(urlString);//构造一个url对象
- } catch (MalformedURLException e) {
- Log.e(TAG, "MalformedURLException");
- e.printStackTrace();
- }
- if(url!=null){
- try {
- HttpURLConnection urlConnection;//使用HttpURLConnection打开连接
- urlConnection = (HttpURLConnection)url.openConnection();
- InputStream stream = urlConnection.getInputStream();//得到读取的内容
- InputStreamReader in = new InputStreamReader(stream);
- BufferedReader buffere = new BufferedReader(in); //为输出创建BufferedReader
- String line = null;
- while((line = buffere.readLine()) != null){//使用while循环来取得获取的数据
- resultData += line + "\n";//我们要在每一行的后面加上一个反斜杠来换行
- }
- if(resultData.equals("")){
- textView.setText("没取到数据");
- }else{
- textView.setText(resultData);
- }
- in.close();//关闭InputStreamReader
- urlConnection.disconnect();//关闭http连接
- } catch (IOException e) {
- Log.e(TAG, "IOException");
- e.printStackTrace();
- }
- }else{
- Log.e(TAG, "url null");
- }
- }
- }
- public class PostActivity extends Activity {
- private String TAG="PostActivity";
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- // TODO Auto-generated method stub
- super.onCreate(savedInstanceState);
- setContentView(R.layout.http);
- TextView textView = (TextView)findViewById(R.id.text);
- String httpUrl = "http://127.0.0.1:8080/test/httpGet.jsp";
- String resultData = "";
- URL url = null;
- try {
- url = new URL(httpUrl);
- } catch (MalformedURLException e) {
- // TODO Auto-generated catch block
- Log.e(TAG, "MalformedURLException");
- e.printStackTrace();
- }
- if(url!=null){
- //使用HttpURLConnection打开连接
- HttpURLConnection urlConnection;
- try {
- urlConnection = (HttpURLConnection)url.openConnection();
- //因为这个是post请求,需要设置为true
- urlConnection.setDoOutput(true);
- urlConnection.setDoInput(true);
- //设置以Post方法
- urlConnection.setUseCaches(false);
- urlConnection.setInstanceFollowRedirects(true);
- //配置本次连接的Content-type
- urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
- //从url.openConnection()至此的配置必须在connect之前完成,要注意的是:
- //connection.getOutputStream会隐含的进行connect
- urlConnection.connect();
- //DataOutputStream流
- DataOutputStream outputStream = new DataOutputStream(urlConnection.getOutputStream());
- //要上传的参数
- String content = "par=" + URLEncoder.encode("ABCD", "gb2312");
- //将要上传的内容写入流中
- outputStream.writeBytes(content);
- //刷新,关闭
- outputStream.flush();
- outputStream.close();
- //取得数据
- BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
- String line = null;
- //使用循环体来获得数据
- while((line = reader.readLine())!=null){
- resultData += line + "\n";
- }
- if(!resultData.equals("")){
- textView.setText(resultData);
- }else{
- textView.setText("读取的内容为null");
- }
- reader.close();
- //关闭http连接
- urlConnection.disconnect();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- Log.e(TAG, "IOException");
- e.printStackTrace();
- }
- }else{
- Log.e(TAG, "url null");
- }
- }
- }
3、获取网络图片的代码:
- public class ImageActivity extends Activity {
- private String TAG = "ImageActivity";
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- // TODO Auto-generated method stub
- super.onCreate(savedInstanceState);
- setContentView(R.layout.image);
- ImageView imageView = (ImageView)findViewById(R.id.image);
- Button button = (Button)findViewById(R.id.button);
- button.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- Intent intent = new Intent(ImageActivity.this, MainActivity.class);
- startActivity(intent);
- }
- });
- String urlString = "http://www.eoeandroid.com/data/attachment/forum/201107/18/142935bbi8d3zpf3d0dd7z.jpg";
- URL imageUrl = null;
- Bitmap bitmap = null;
- try{
- imageUrl = new URL(urlString);
- }catch (MalformedURLException e) {
- // TODO: handle exception
- Log.e(TAG, "MalformedURLException");
- e.printStackTrace();
- }
- try{
- HttpURLConnection connection = (HttpURLConnection)imageUrl.openConnection();
- connection.setDoInput(true);
- connection.connect();
- //将得到的数据转换为InputStream
- InputStream is = connection.getInputStream();
- //将InputStream转换为Bitmap
- bitmap = BitmapFactory.decodeStream(is);
- is.close();
- }catch (IOException e) {
- // TODO: handle exception
- Log.e(TAG, "IOException");
- }
- if(bitmap == null){
- Log.i(TAG, "没取到数据");
- }else{
- imageView.setImageBitmap(bitmap);
- }
- }
- }