欢迎使用CSDN-markdown编辑器

HttpConnection 网络请求

1、项目列表
放图
欢迎使用CSDN-markdown编辑器_第1张图片
2、HttpUtils
详细
package com.example.demohttp;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import android.util.Log;

/**
 * 网络请求 get
 * 
 * @author YAH
 * 
 */
public class HttpUtils {

    /**
     * http get请求
     * 
     * @param urlpath
     *            请求的url
     * @return
     */
    public static String sendHttpGetRequest(String urlpath) {
        Log.i("iiiiiiiiii", "======================sendHttpGetRequest:");
        HttpURLConnection conn = null;
        try {
            // 一般都需要进行URLEncoder.encode(urlpath, "utf-8"); 若返回码为505
            // 可以试着用URLEncoder.encode这个方法
            String url2 = URLEncoder.encode(urlpath, "utf-8");
            Log.i("iiiiiiiiii", "======================url2==:" + url2);
            URL url = new URL(urlpath);
            conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            conn.setReadTimeout(5000);
            conn.setReadTimeout(5000);
            conn.setRequestMethod("GET");
            int reponseCode = conn.getResponseCode();
            Log.i("iiiiiiiiii", "======================返回码为::" + reponseCode);
            while (reponseCode == 200) {
                InputStream is = conn.getInputStream();
                //解析获得的字符串  方式一:
                // BufferedReader reader = new BufferedReader(
                // new InputStreamReader(is));
                // StringBuilder builder = new StringBuilder();
                // String buff = "";
                // while ((buff = reader.readLine()) != null) {
                // builder.append(buff);
                // }
                // return builder.toString();

                //解析获得的字符串  方式二:
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buff = new byte[3072];
                int len = 0;
                while ((len = is.read(buff)) != -1) {
                    baos.write(buff, 0, len);
                }
                baos.close();
                is.close();
                byte[] bytearray = baos.toByteArray();
                Log.i("iiiiiiiiii", "======================返回数据解析为::"+ new String(bytearray));

                return new String(bytearray);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        return null;
    }
}

注意!你给的url 有时候需要进行解码 即URLEncoder.encode(urlpath, “utf-8”)这个方法,如果说你没有进行解码的话,给你的返回码是505,那么你应该试着用一下,不过大多数情况下不用,用来反而又出错。不要问我怎么知道的,两个多小时的找bug真的很难受!


MainActivity

package com.example.demohttp;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

    private Button btn;
    private TextView txt;
    private String strRe = "";
    private String url ="http://360.hao245.com/";
    private Handler handler;
    private int HTTPGETSENDMES =0x11;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txt =(TextView)findViewById(R.id.text);
        btn =(Button)findViewById(R.id.btn);
        Log.i("iiiiiiiiii", "======================initUI:");
        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                new Thread() {
                    public void run() {
                        Log.i("iiiiiiiiii", "======================run:");
                    strRe=HttpUtils.sendHttpGetRequest(url);
                    Log.i("iiiiiiiiii", "=====================after=run:"+strRe);
                    Message msg=new Message();
                    msg.obj=strRe;
                    msg.what=HTTPGETSENDMES;
                    handler.sendMessage(msg);
                    };
                }.start();
            }
        });


        handler =new Handler(){
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case 0x11:
                    //由于是网页端,采取解析html的方式解码显示在textview上面
                    txt.setText(Html.fromHtml(""+strRe));
                    break;

                default:
                    break;
                }
            }
        };
    }

}

调用应该没什么问题吧。


看下布局

"http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.demohttp.MainActivity" >


    
3、不要忘记给权限

权限以及Theme(ps:怎么说呢,其实Theme你不用改,但是我就是看actionbar不顺眼,每个项目都砍掉它了的)

 "android.permission.INTERNET" />
 "true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.DeviceDefault.Light.NoActionBar" >
4、效果
真机测试
欢迎使用CSDN-markdown编辑器_第2张图片

你可能感兴趣的:(技术流)