安卓网络请求只Get和Post

来源:互联网 发布:关于公主的网络名言 编辑:程序博客网 时间:2024/05/09 19:13

用的是apache httpClient:

首先,记得在AndroidManifest.xml中添加网络请求的权限

 <uses-permission android:name="android.permission.INTERNET"></uses-permission>

get请求:

1.HttpClient client = new DefaultHttpClient();    

2.HttpGet get = new HttpGet(url); 

3.HttpResponse response = client.execute(get);

4.HttpEntity entity = response.getEntity();

5.InputStream inputStream = entity.getContent();

代码如下:

package com.example.httpgettest;import java.io.BufferedReader;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.MalformedURLException;import java.net.URI;import java.net.URISyntaxException;import java.net.URL;import javax.net.ssl.HttpsURLConnection;import org.apache.http.*;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;import android.os.AsyncTask;import android.os.Bundle;import android.app.Activity;import android.view.Menu;import android.view.TextureView;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;public class MainActivity extends Activity {private TextView textView;private Button button;private String resultString = "";private String urlString ;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);textView = (TextView)findViewById(R.id.text_view);button = (Button)findViewById(R.id.button);button.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubDown down = new Down();urlString = "http://www.baidu.com";down.execute(urlString);}});}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}class Down extends AsyncTask<String, Integer, String>{@Overrideprotected String doInBackground(String... params) {// TODO Auto-generated method stubtry {HttpClient client = new DefaultHttpClient();                    HttpGet get = new HttpGet(params[0]);                    HttpResponse response = client.execute(get);if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {                        HttpEntity entity = response.getEntity();                        InputStream inputStream = entity.getContent();                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream);                    BufferedReader in = new BufferedReader(inputStreamReader);                      String inputLine="";                                        while((inputLine=in.readLine())!=null){                        resultString+=inputLine+"\n";                    }                    return resultString;                  }} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}    return null;}@Overrideprotected void onPostExecute(String result) {// TODO Auto-generated method stubsuper.onPostExecute(result);textView.setText(result);}//onPreExecute方法用于在执行后台任务前做一些UI操作            @Override            protected void onPreExecute() {                  textView.setText("loading...");            }  }}


<span style="font-family:Microsoft YaHei;"><?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.httpgettest"    android:versionCode="1"    android:versionName="1.0" >    <uses-permission android:name="android.permission.INTERNET"></uses-permission>    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="15" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name=".MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest></span>
<span style="font-family:Microsoft YaHei;"><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"    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=".MainActivity" >    <Button android:id="@+id/button"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="httpGet"></Button>    <TextView android:id="@+id/text_view"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_below="@id/button"        android:textSize="20sp"        android:textColor="@android:color/darker_gray"        android:scrollbars="vertical"/></RelativeLayout></span>

post请求:

1.HttpClient httpClient = new DefaultHttpClient();

2.HttpPost httpPost = new HttpPost(url);

3.List<NameValuePair>HttpEntity httpEntity = new UrlEncodedFormEntity(entityList);    entityList = new ArrayList<NameValuePair>();

4.httpPost.setEntity(httpEntity);

5.HttpResponse response = httpClient.execute(httpPost);

6.InputStream inputStream = response.getEntity().getContent();

代码如下:

<span style="font-family:Microsoft YaHei;">package com.example.httpposttest;import java.io.BufferedReader;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import java.util.ArrayList;import java.util.List;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;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.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.impl.conn.DefaultClientConnection;import org.apache.http.message.BasicNameValuePair;import android.os.AsyncTask;import android.os.Bundle;import android.os.Environment;import android.app.Activity;import android.view.Menu;import android.view.View;import android.widget.ArrayAdapter;import android.widget.Button;import android.widget.ProgressBar;import android.widget.TextView;public class MainActivity extends Activity {private Button button;private TextView textView;private ProgressBar progressBar;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);button = (Button)findViewById(R.id.button);textView = (TextView)findViewById(R.id.text_view);progressBar = (ProgressBar)findViewById(R.id.progress_bar);button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubHttpPostAsy post = new HttpPostAsy();post.execute("http://www.baidu.com");}});}class HttpPostAsy extends AsyncTask<String, Integer, String>{@Overrideprotected void onProgressUpdate(Integer... values) {// TODO Auto-generated method stubsuper.onProgressUpdate(values);if(values[0] == 100){progressBar.setVisibility(View.GONE);}else {progressBar.setProgress(values[0]);}}@Overrideprotected void onPreExecute() {// TODO Auto-generated method stubsuper.onPreExecute();textView.setText("loading...");}@Overrideprotected void onPostExecute(String result) {// TODO Auto-generated method stubsuper.onPostExecute(result);textView.setText(result);}@Overrideprotected String doInBackground(String... params) {// TODO Auto-generated method stubHttpClient httpClient = new DefaultHttpClient();HttpPost httpPost = new HttpPost(params[0]);List<NameValuePair> entityList = new ArrayList<NameValuePair>();//entityList.add( new BasicNameValuePair("username", ""));try {HttpEntity httpEntity = new UrlEncodedFormEntity(entityList);httpPost.setEntity(httpEntity);HttpResponse response = httpClient.execute(httpPost);if (null == response)        {            return "null";        }long totallength = response.getEntity().getContentLength();InputStream inputStream = response.getEntity().getContent();String filePath = null;      boolean hasSDCard = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);      if (hasSDCard) {      System.out.println("*do not have sd card*");        filePath = Environment.getExternalStorageDirectory().toString() + File.separator + "a.txt";      } else  {    filePath = Environment.getDownloadCacheDirectory().toString() + File.separator + "a.txt";    }File file = new File(filePath);if(!file.exists()){System.out.println("*file not exist*");File pFile = file.getParentFile();pFile.mkdirs();file.createNewFile();}ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();FileOutputStream fileOutputStream = new FileOutputStream(file);byte[] buffer = new byte[1024];            String result = "";            String line = "";            int count = 0;            int length = -1;                while ((length=inputStream.read(buffer))!=-1)            {            byteArrayOutputStream.write(buffer, 0, length);            fileOutputStream.write(buffer);            count = count +length;            publishProgress((int) ((count / (float) totallength) * 100));                  for (int i = 0; i < buffer.length; i++) {result = result + buffer[i];}            }            return result;} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return "null";}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}</span>

<span style="font-family:Microsoft YaHei;"><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"    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=".MainActivity" >    <Button android:id="@+id/button"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="httpPost"/>    <ProgressBar android:id="@+id/progress_bar"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_below="@id/button"        style="?android:attr/progressBarStyleHorizontal" />    <ScrollView android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_below="@id/progress_bar">         <TextView android:id="@+id/text_view"        android:layout_width="fill_parent"        android:layout_height="wrap_content"/>    </ScrollView>   </RelativeLayout></span>




0 0
原创粉丝点击