Android——访问网络谷歌2013官方工具

来源:互联网 发布:meanshift算法opencv 编辑:程序博客网 时间:2024/06/05 02:47

Android——访问网络谷歌2013官方工具


http://localhost:8080/        127.0.0.1



<span style="font-size:18px;"><strong>package com.example.jreduch07.util;import android.util.Log;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;/** * Created by 冲天之峰 on 2016/8/17. */public class HttpUtil {    public static  String HttpGet(String uri){        HttpURLConnection con = null;//为了抛异常        InputStream is = null;        BufferedReader reader=null;        String result=null;        StringBuffer sbf=new StringBuffer();        try {            URL url = new URL(uri);            con = (HttpURLConnection) url.openConnection();            con.setRequestProperty("apikey","5b46143955a4b1ff1b470a94315625cd");            con.setConnectTimeout(5 * 1000);            con.setReadTimeout(5 * 1000);            //http响应码200成功 404未找到 500发生错误            if (con.getResponseCode() == 200) {                is = con.getInputStream();                reader =new BufferedReader(new InputStreamReader(is,"UTF-8"));                String strRead=null;                while ((strRead = reader.readLine())!=null) {                    sbf.append(strRead);                    sbf.append("\r\n");                    Log.d("==j==", "200");                }                reader.close();                result=sbf.toString();                Log.d("=====",result);            }        } catch (MalformedURLException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        } finally {            if (is != null) {                try {                    is.close();                } catch (IOException e) {                    e.printStackTrace();                }            }if (con != null) {                con.disconnect();            }        }        return result;    }    }</strong></span>
<span style="font-size:18px;"><strong>package com.example.jreduch07.util;/** * Created by 冲天之峰 on 2016/8/17. */public class UrlUtil {    //获取 频道的网络接口    public static String channelUrl = "http://apis.baidu.com/showapi_open_bus/channel_news/channel_news";    /*获取 频道对应新闻的网络接口      get 请求参数:       channelId    : 新闻频道id,必须精确匹配       channelName  :新闻频道名称,可模糊匹配       title        :新闻标题,模糊匹配       page         :页数,默认1。每页最多20条记       needContent  : 是否需要返回正文,1为需要       needHtml     :是否需要返回正文的html格式,1为需要     */    public static String newsUrl = "http://apis.baidu.com/showapi_open_bus/channel_news/search_news";/*参数名类型必填参数位置描述默认值location string是urlParam所查询的位置 beijinglanguage string否urlParam语言zh-Hansunit string否urlParam单位cstart string否urlParam起始时间0days string否urlParam天数3 */    //获取天气的 网络接口    public  static  String weatherUrl="http://apis.baidu.com/thinkpage/weather_api/suggestion";}</strong></span>
<span style="font-size:18px;"><strong>package com.example.jreduch07.util;import com.android.volley.AuthFailureError;import com.android.volley.Response;import com.android.volley.toolbox.StringRequest;import java.util.HashMap;import java.util.Map;/** * Created by 冲天之峰 on 2016/8/25. */public class StringGetRequest extends StringRequest {    private Map<String,String> header;    public StringGetRequest(int method, String url, Response.Listener<String> listener, Response.ErrorListener errorListener) {        super(method, url, listener, errorListener);        header=new HashMap<>();    }public  void  putHeaders(String key,String value){    header.put(key,value);}    @Override    public  Map<String,String> getHeaders() throws AuthFailureError{        return  header;    }////    public StringGetRequest(String url, Response.Listener<String> listener, Response.ErrorListener errorListener) {//        super(url, listener, errorListener);//    }}</strong></span>

<span style="font-size:18px;"><strong>package com.example.jreduch07.util;import com.android.volley.AuthFailureError;import com.android.volley.Response;import com.android.volley.Response.Listener;import com.android.volley.toolbox.StringRequest;import java.util.HashMap;import java.util.Map;public class StringPostRequest extends StringRequest {private Map<String, String> params;private Map<String,String> header;public StringPostRequest(String url, Listener<String> listener, Response.ErrorListener errorListener) {super(Method.POST, url, listener, errorListener);params = new HashMap<String, String>();header = new HashMap<String, String>();}@Overridepublic Map<String, String> getHeaders() throws AuthFailureError {return header;}public  void putHeaders(String key,String value){this.header.put(key,value);}@Overrideprotected Map<String, String> getParams() throws AuthFailureError {return params;}public void putParams(String key, String value){this.params.put(key, value);}}</strong></span>
1111111111111111111111111
<span style="font-size:18px;"><strong>package com.example.jreduch07;import android.os.AsyncTask;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;public class HttpActivity extends AppCompatActivity {public EditText  et;    private Button search;    private Button search1;    private TextView show;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_http);        et=(EditText)findViewById(R.id.et);        search=(Button)findViewById(R.id.search);        search1=(Button)findViewById(R.id.search1);        show=(TextView)findViewById(R.id.show);        search.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                String url="http://192.168.1.48:8080/HttpTest/index.jsp?option=getUser&uName=jerehedu";                new  MyGetJob().execute(url);            }        });        search1.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                String[] arg=new String[2];                arg[0]="http://192.168.1.48:8080/HttpTest/index.jsp";                arg[1]="option=getUser&uName=jerehedu";                new MyPostJob1().execute(arg);            }        });    }    private  class MyPostJob1 extends AsyncTask<String,Void,String>{    @Override    protected String doInBackground(String... strings) {        HttpURLConnection con=null;        InputStream is=null;        StringBuilder sbd=new StringBuilder();        try {            URL url=new URL(strings[0]);            con= (HttpURLConnection) url.openConnection();            con.setConnectTimeout(5*1000);            con.setReadTimeout(5*1000);            con.setRequestMethod("POST");            con.setDoInput(true);            con.setDoOutput(true);            con.setUseCaches(false);            con.setRequestProperty("Charset","UTF-8");            con.setRequestProperty("Content-type","application/x-www-form-urlencoded");//            con.setRequestProperty("Charset","UTF-8");//            con.setRequestProperty("Content-type","application/x-www-from-urlencoded");            //params应该是这样的=》option=getUser&uName=jerehedu            String params=strings[1];            OutputStream os=con.getOutputStream();   //数据传输  流            os.write(params.getBytes());            os.flush();            os.close();            if (con.getResponseCode()==200) {              is=con.getInputStream();                int next = 0;                byte[] b = new byte[1024];                while ((next = is.read(b)) > 0) {                    sbd.append(new String(b, 0, next));                }            }        } catch (MalformedURLException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }finally {            if (is!=null){                try {                    is.close();                } catch (IOException e) {                    e.printStackTrace();                }                if (con!=null){                    con.disconnect();  //断开连接                }            }        }        return sbd.toString();    }    @Override    protected void onPostExecute(String s) {        super.onPostExecute(s);        show.setText("POST请求结果:"+s);    }}    /*    AsyncTask异步任务类    异步任务类的第一个参数会传到doInBackground方法中    第三个参数              #指定doINBackground方法的返回值              #doINBackground方法的返回值会被OnPostExecute接收     */        private class MyGetJob extends AsyncTask<String, Void, String> {            //onPreExecute在主线程中执行命令            //进度条的初始化            @Override            protected void onPreExecute() {                super.onPreExecute();            }            //doInBackground在子线程中执行名命令            @Override            protected String doInBackground(String... strings) {                HttpURLConnection con = null;                InputStream is = null;                StringBuilder sbd = new StringBuilder();                try {                    URL url = new URL(strings[0]);                    con = (HttpURLConnection) url.openConnection();                    con.setConnectTimeout(5 * 1000);                    con.setReadTimeout(5 * 1000);                /*                *http相应200:成功                * 404未找到                * 500发生错误                 */                    if (con.getResponseCode() == 200) {                        is = con.getInputStream();                        int next = 0;                        byte[] bt = new byte[1024];                        while ((next = is.read(bt)) > 0) {                            sbd.append(new String(bt, 0, next));                        }                    }                } catch (MalformedURLException e) {                    e.printStackTrace();                } catch (IOException e) {                    e.printStackTrace();                } finally {                    if (is != null) {                        try {                            is.close();                        } catch (IOException e) {                            e.printStackTrace();                        }                        if (con != null) {                            con.disconnect();  //断开连接                        }                    }                }                return sbd.toString();            }            //onPostExecute在UI线程中执行命令  主线程            @Override            protected void onPostExecute(String s) {                super.onPostExecute(s);                show.setText(s);            }        }    }</strong></span>
<span style="font-size:18px;"><strong><?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.example.jreduch07.HttpActivity">    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="姓名!"        android:textSize="20dp"        android:layout_alignTop="@+id/et"        android:layout_alignParentStart="true"        android:layout_alignBottom="@+id/et"        android:id="@+id/textView" />    <EditText        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:hint="请输入要查找姓名"        android:id="@+id/et"        android:layout_alignBottom="@+id/search"        android:layout_centerHorizontal="true" />    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="查询(GET方法)"        android:id="@+id/search"        android:layout_alignParentTop="true"        android:layout_alignParentEnd="true" />    <TextView        android:layout_width="match_parent"        android:layout_height="150dp"        android:background="#fff30d"        android:id="@+id/show"        android:textSize="30sp"        android:text="查询结果:"        android:layout_below="@+id/search1"        android:layout_alignParentStart="true" />    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="查询(post方法)"        android:id="@+id/search1"        android:layout_below="@+id/et"        android:layout_alignParentEnd="true" /></RelativeLayout></strong></span>

222222222222222

<span style="font-size:18px;"><strong>package com.example.jreduch07;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Button;import android.widget.TextView;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.VolleyError;import com.android.volley.toolbox.StringRequest;import com.android.volley.toolbox.Volley;import com.example.jreduch07.util.StringPostRequest;import com.example.jreduch07.util.UrlUtil;public class VolleyActivity extends AppCompatActivity implements View.OnClickListener{private Button bt;    private TextView tv;    private RequestQueue queue;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_volley);        bt=(Button)findViewById(R.id.bt);        tv=(TextView)findViewById(R.id.tv);        bt.setOnClickListener(this);        //初始化Volley请求队列        queue= Volley.newRequestQueue(this);    }    public  void onClick(View view){        int id=view.getId();        if (id==R.id.bt){           PostVolley();        }    }    public  void GetVolly(){        //第二步  写请求        String url="http://172.20.180.5:8080/HttpTest/index.jsp?option=getUser&uName=jerehedu";        StringRequest sr=new StringRequest(url, new Response.Listener<String>() {            @Override            public void onResponse(String s) {           tv.setText(s);            }        }, new Response.ErrorListener() {            @Override            public void onErrorResponse(VolleyError volleyError) {         tv.setText(volleyError.getMessage());            }        });        //第三步把请求放到Queue        queue.add(sr);    }public  void  PostVolley(){    String url= UrlUtil.channelUrl;    StringPostRequest spr=new            StringPostRequest(url, new Response.Listener<String>() {        @Override        public void onResponse(String s) {tv.setText(s);        }    }, new Response.ErrorListener() {        @Override        public void onErrorResponse(VolleyError volleyError) {        }    });    spr.putHeaders("apikey","5b46143955a4b1ff1b470a94315625cd");//    spr.putParams("channelId",);//    spr.    queue.add(spr);}}</strong></span><span style="font-size:24px;font-weight: bold;"></span>

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.example.jreduch07.VolleyActivity"><Button    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:text="访问网络"    android:gravity="center"    android:id="@+id/bt"    />    <TextView        android:layout_width="match_parent"        android:layout_height="match_parent"        android:id="@+id/tv"        android:layout_below="@+id/bt"        /></RelativeLayout>





1 0