URLConnection/Android Stutio中HttpClient的添加jar包方法和DoGet、DoPost的用法
来源:互联网 发布:黑马程序员java视频 编辑:程序博客网 时间:2024/06/04 19:05
网络连接操作是一种耗时操作,因此不能再UI主线程中进行网络连接操作,需要另外开启一个线程来进行网络连接操作,开启线程的方法一种的直接开启一个新的线程即 newThread(new Runable{…})另一种是使用AsyncTask方法,在该方法中的DoInBackground()方法中进行连接网络的操作,因为AsyncTask会自动开启一个线程,所以就不用重新建立一个线程,只需要创建该AsyncTask对象然后调用execute()方法就可以了。
URLConnection创建和使用
1.创建一个新的URL,然后打开连接返回一个URLConnection对象,然后将该对象得到的内容读出来,显示到一个TextView上
try { URL url=new URL("http://www.360.com"); URLConnection connection=url.openConnection();//打开连接 InputStream is=connection.getInputStream();//获取输入流 BufferedReader br=new BufferedReader(new InputStreamReader(is)); String line=br.readLine(); StringBuffer buffer=new StringBuffer();//StringBuffer可以在字符串后面接上字符串使之成为连续的字符串 while (line!=null){ Log.d("0", line); buffer.append(line); line=br.readLine(); } //子线程向主线程传递消息的方法 Message msg=handler.obtainMessage(); msg.what=URL_CONNECT;//设置类型,一般为一个静态的int类型值 msg.obj=buffer.toString().trim();//将得到的信息转换为String类型,并将里面的空格删掉 handler.sendMessage(msg);//发送消息给Handler,通过Handler对UI主线程进行操作 br.close(); is.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
2.子线程通过主线程传递消息是靠Handler来完成的,通过上面的sendMessage()方法将得到的Message进行解析,将得到的信息放到TextView中显示
private Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what){ case URL_CONNECT: String content= (String) msg.obj.toString(); mTextViewConnection.setText(content);//得到的内容显示到文本中去 break; default: break; } } };
3.最后开启一个线程,来进行网络连接的操作
//打开网络连接时一种耗时操作,UI主线程中不允许进行耗时操作,因此需要重新开始一个线程 new Thread(new Runnable() { @Override public void run() { urlConnection(); } }).start()
HttpClient添加client的Jar包的方法
File→Project Structure→Dependencies→右边有个“+”点击然后选择第一个Library Dependence 最后在文本框中输入org.apcahe.http点击搜索,选中第一个点击OK添加进去就可以使用httpClient了
HttpClient的DoGet方法
1.首先创建一个类HTTPDoGetAsyncTask 然后继承于AsyncTask,然后填写里面的3个参数,这三个参数分别是doInBackground和onProgressUpdate以及onPostExecute的参数列表的类型
2.然后在doInBackground中(该方法会自动创建一个新的线程进行操作)先创建一个HttpClient对象然后设置为Get方法,然后读取返回的信息
/*** * 尖括号内的三个参数分别传入doInBackground和onProgressUpdate以及onPostExecute的参数列表的类型 */ class HTTPDoGetAsyncTask extends AsyncTask<String,Integer,String>{ @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); } @Override protected String doInBackground(String... params) { HttpClient client=new DefaultHttpClient(); //利用eclipse中的网络开启一个服务器,向服务器提交数据, String url="http://192.168.0.103:8080/ElevenAugMyServer/MyServerLet?username=ni&password=123456"; HttpGet get=new HttpGet(url); get.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//设置服务器接收后数据的读取方式为utf8 try { HttpResponse response=client.execute(get);//执行get方法得到服务器的返回的所有数据都在response中 StatusLine statusLine=response.getStatusLine();//httpClient访问服务器返回的表头,包含http状态码 int code=statusLine.getStatusCode();//得到状态码 if (code== HttpURLConnection.HTTP_OK){ HttpEntity entity=response.getEntity();//得到数据的实体 InputStream is=entity.getContent();//得到输入流 BufferedReader br=new BufferedReader(new InputStreamReader(is)); String line=br.readLine(); while (line!=null){ Log.d("line",line); br.readLine(); } } } catch (IOException e) { e.printStackTrace(); } return "连接成功"; } }
最后要调用该类,然后执行
HTTPDoGetAsyncTask task=new HTTPDoGetAsyncTask(); task.execute(); Toast.makeText(HTTPClient.this, "点击了DoGet", Toast.LENGTH_SHORT).show(); break;
HttpClient的DoPost方法
1.首先创建一个类HTTPDoGetAsyncTask 然后继承于AsyncTask,然后填写里面的3个参数,这三个参数分别是doInBackground和onProgressUpdate以及onPostExecute的参数列表的类型
2.然后在doInBackground中(该方法会自动创建一个新的线程进行操作)先创建一个HttpClient对象然后设置为Post方法,然后将数据封装到一个List中,然后用post封装为实体,在执行execute方法执行post方法
3.读取返回的信息
class HTTPDoPostAsyncTask extends AsyncTask<String,Integer,String>{ @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); } @Override protected String doInBackground(String... params) { HttpClient client=new DefaultHttpClient(); String url="http://192.168.0.103:8080/ElevenAugMyServer/MyServerLet"; HttpPost post=new HttpPost(url); NameValuePair pair=new BasicNameValuePair("username","zhangsan"); NameValuePair pair1=new BasicNameValuePair("password","123456"); ArrayList<NameValuePair> param=new ArrayList<>();//创建ArrayList数组 param.add(pair); param.add(pair1); try { post.setEntity(new UrlEncodedFormEntity(param,"UTF-8"));//创建一个实体,将ArrayList封装为UTF-8的类型 post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//设置服务器接收数据后的读取方式为UTF-8 HttpResponse response=client.execute(post);//执行post方法得到服务器的返回的所有数据都在response中 int code=response.getStatusLine().getStatusCode();//httpClient访问服务器返回的表头,包含http状态码,并得到状态码 if (code==HttpURLConnection.HTTP_OK){ HttpEntity entity=response.getEntity();//得到数据的实体 InputStream is=entity.getContent();//得到输入流 BufferedReader br=new BufferedReader(new InputStreamReader(is)); String line=br.readLine(); while (line!=null){ Log.d("line",line); br.readLine(); } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "连接成功"; } }
4.最后调用execute方法
HTTPDoPostAsyncTask taskDoPost=new HTTPDoPostAsyncTask(); taskDoPost.execute(); Toast.makeText(HTTPClient.this, "点击了DoPost", Toast.LENGTH_SHORT).show();
- URLConnection/Android Stutio中HttpClient的添加jar包方法和DoGet、DoPost的用法
- HttpClient 连接网络的两种方法doGet和doPost
- HttpUrlConnection和HttpClient的使用(doGet( )、doPost( )方法)
- httpclient的dopost和doget请求
- doget和dopost方法的意思,为什么在servlet中dopost中调用doget方法
- servlet 的doGet()和doPost()方法
- doPost和doGet方法的区别
- 【JavaEE】Servlet的doGet()和doPost()方法
- jsp中doGet和doPost的区别
- Servlet中doGet 和 doPost的区别
- servlet中doGet()和doPost()的区别
- servlet中doGet()和doPost()的区别
- android 中HttpClient和URLConnection的区别
- dopost和doget的区别
- doGet()和doPost()的区别
- doGet()和doPost()的区别
- doGet和doPost的区别
- doGet和doPost的区别
- UI 第六节 uisegmentedControl uiimage uislider 课后习题
- NSScanner: nil string argument
- Dimensionality Reduction(学习Free Mind知识整理)
- capture screen activity to a movie file using AV Foundation on OS X 10.7 Lion and later
- mybatis调用存储过程
- URLConnection/Android Stutio中HttpClient的添加jar包方法和DoGet、DoPost的用法
- 自定义MITK PlanarFigure及困惑
- 宏定义以及例子
- hdu2824 The Euler function
- [疑似官泄] 某Ri牌示波器固件破解
- Exbox上的相关链接
- hdu5446
- centos 7 防火墙和端口配置
- java虚拟机的面试问题