Android的Http通信加载页面、下载图片 以及doGet、doPost请求服务器

来源:互联网 发布:淘宝怎么看卖家电话 编辑:程序博客网 时间:2024/06/05 20:52


*********************************通过HttpUrl通信加载百度页面*********************************

activity_main.xml

<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.androidhttpdemo.MainActivity" >    <WebView        android:id="@+id/webView"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:layout_marginTop="168dp" /></RelativeLayout>


HttpThread

package com.example.androidhttpdemo;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import android.os.Handler;import android.webkit.WebView;public class HttpThread extends Thread {private String url;private WebView webView;private Handler handler;public HttpThread(String url, WebView webView, Handler handler) {super();this.url = url;this.webView = webView;this.handler = handler;}@Overridepublic void run() {super.run();try {URL httpUrl = new URL(url);HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();connection.setReadTimeout(5000);connection.setRequestMethod("GET");// 缓冲final StringBuffer buffer = new StringBuffer();// 包装流BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));String string;while ((string = reader.readLine()) != null) {buffer.append(string);}/** * 发送消息 */handler.post(new Runnable() {@Overridepublic void run() {//加载信息webView.loadData(buffer.toString(),"text/html;charset=utf-8", null);}});} catch (Exception e) {e.printStackTrace();}}}

MainActivity

package com.example.androidhttpdemo;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.view.Menu;import android.view.MenuItem;import android.webkit.WebBackForwardList;import android.webkit.WebView;import android.widget.ImageView;public class MainActivity extends Activity {private WebView webView;private Handler handler = new Handler();@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);webView =(WebView) findViewById(R.id.webView);new HttpThread("http://www.baidu.com", webView, handler).start();}}


***********************************************Http通信下载网络图片到本地,然后更新到页面***********************************

<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.androidhttpdemo.MainActivity" >    <ImageView        android:id="@+id/imageView"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_alignParentTop="true"        android:layout_marginLeft="124dp"        android:layout_marginTop="158dp"        android:src="@drawable/ic_launcher" /></RelativeLayout>
HttpThread

package com.example.androidhttpdemo;import java.io.File;import java.io.FileOutputStream;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Environment;import android.os.Handler;import android.widget.ImageView;public class HttpThread extends Thread {private String url;private ImageView imageView;private Handler handler;public HttpThread(String url, ImageView imageView, Handler handler) {super();this.url = url;this.imageView = imageView;this.handler = handler;}@Overridepublic void run() {super.run();try {URL httpUrl = new URL(url);HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();connection.setReadTimeout(5000);connection.setRequestMethod("GET");connection.setDoInput(true);connection.setDoOutput(true);// 得到可以读取文件的输入流InputStream in = connection.getInputStream();FileOutputStream out = null;File downLoadFile = null;// 文件目录String fileName = String.valueOf(System.currentTimeMillis());if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {// sd卡目录File parent = Environment.getExternalStorageDirectory();downLoadFile = new File(parent, fileName);out = new FileOutputStream(downLoadFile);}byte[] b = new byte[1024];int len;if (out != null) {while ((len = in.read(b)) != -1) {out.write(b, 0, len);}}final Bitmap bitmap = BitmapFactory.decodeFile(downLoadFile.getAbsolutePath());;handler.post(new Runnable() {@Overridepublic void run() {// 更新主线程imageView.setImageBitmap(bitmap);}});} catch (Exception e) {e.printStackTrace();}}}

package com.example.androidhttpdemo;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.widget.ImageView;public class MainActivity extends Activity {private ImageView imageView;private Handler handler = new Handler();@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);imageView = (ImageView) findViewById(R.id.imageView);new HttpThread("网上图片地址", imageView, handler).start();}}

******************************************************请求服务器doGet  doPost(代码没有测试)*****************************************

<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.androidhttpdemo.MainActivity" >    <TextView        android:id="@+id/textView2"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_alignParentTop="true"        android:layout_marginTop="21dp"        android:text="nama" />    <TextView        android:id="@+id/textView1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentTop="true"        android:layout_marginTop="66dp"        android:layout_toLeftOf="@+id/editText1"        android:text="age" />    <EditText        android:id="@+id/et_age"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignBottom="@+id/textView1"        android:layout_centerHorizontal="true"        android:ems="10" />    <Button        android:id="@+id/button"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_below="@+id/textView1"        android:layout_marginTop="52dp"        android:layout_toRightOf="@+id/textView1"        android:text="Button" />    <EditText        android:id="@+id/et_name"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignBottom="@+id/textView2"        android:layout_alignLeft="@+id/et_age"        android:ems="10" /></RelativeLayout>
MainActivity

package com.example.androidhttpdemo;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;public class MainActivity extends Activity {private EditText age;private EditText name;private Button button;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);age = (EditText) findViewById(R.id.et_age);name = (EditText) findViewById(R.id.et_name);button = (Button) findViewById(R.id.button);button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {String url = "http://192.168.1.102:8080/web/MyServlet";new HttpThread(url, name.getText().toString(), age.getText().toString()).start();}});}}

HttpThread

package com.example.androidhttpdemo;import java.io.BufferedReader;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.net.URLEncoder;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Environment;import android.os.Handler;import android.util.Log;import android.widget.ImageView;public class HttpThread extends Thread {private String url;private String name;private String age;public HttpThread(String url, String name, String age) {super();this.url = url;this.name = name;this.age = age;}private void doGet() {// doGet方式,传递url,显示出来try {url = url + "?name=" + URLEncoder.encode(name, "utf-8") + "&age="+ age;} catch (UnsupportedEncodingException e1) {e1.printStackTrace();}try {URL httpUrl = new URL(url);HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();connection.setReadTimeout(5000);connection.setRequestMethod("GET");BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));String str;StringBuffer sb = new StringBuffer();while ((str = reader.readLine()) != null) {sb.append(str);}// 将服务器返回的数据打印出来Log.e("TAG", "" + sb.toString());} catch (Exception e) {}}private void doPost() {URL httpUrl = null;try {try {httpUrl = new URL(url);HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();connection.setReadTimeout(5000);connection.setRequestMethod("POST");OutputStream out = connection.getOutputStream();// 发送的实体数据,是通过outPut发送的,post不用转码,android默认utf-8编码的String content = "name=" + name + "&age=" + age;out.write(content.getBytes());/** * 接受服务器数据 */BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));StringBuffer sb = new StringBuffer();String str;while ((str = reader.readLine()) != null) {sb.append(str);}Log.e("TAG", "" + sb.toString());} catch (IOException e) {e.printStackTrace();}} catch (Exception e) {e.printStackTrace();}}@Overridepublic void run() {super.run();doGet();doPost();}}

*******************************************httpClient**(代码没有测试)******************************************

布局不变

MainActivity

package com.example.androidhttpdemo;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;public class MainActivity extends Activity {private EditText age;private EditText name;private Button button;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);age = (EditText) findViewById(R.id.et_age);name = (EditText) findViewById(R.id.et_name);button = (Button) findViewById(R.id.button);button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {String url = "http://192.168.1.102:8080/web/MyServlet";url = url + "?name=" + name.getText().toString() + "&age="+ age.getText().toString();//get方法new HttpClientThread(url).start();//post方法new HttpClientThread(url, name.getText().toString(), age.getText().toString()).start();}});}}


package com.example.androidhttpdemo;import java.io.BufferedReader;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.net.URLEncoder;import java.util.ArrayList;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.NameValuePair;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Environment;import android.os.Handler;import android.util.Log;import android.widget.ImageView;public class HttpClientThread extends Thread {private String url;private String name;private String age;public HttpClientThread(String url) {super();this.url = url;}public HttpClientThread(String url, String name, String age) {super();this.url = url;this.name = name;this.age = age;}private void doHttpClientPost() {HttpPost httpPost = new HttpPost(url);// 获取对象HttpClient client = new DefaultHttpClient();ArrayList<NameValuePair> list = new ArrayList<NameValuePair>();list.add(new BasicNameValuePair("name", name));list.add(new BasicNameValuePair("age", age));try {httpPost.setEntity(new UrlEncodedFormEntity(list));HttpResponse response = client.execute(httpPost);if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {String content = EntityUtils.toString(response.getEntity());Log.e("TAG", "" + content);}} catch (Exception e) {e.printStackTrace();}}private void doHttpClientGet() {HttpGet httpGet = new HttpGet(url);// 获取对象HttpClient client = new DefaultHttpClient();try {HttpResponse response = client.execute(httpGet);if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {String content = EntityUtils.toString(response.getEntity());Log.e("TAG", "" + content);}} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}@Overridepublic void run() {super.run();doHttpClientGet();doHttpClientPost();}}





0 0
原创粉丝点击