安卓网络请求只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>
- 安卓网络请求只Get和Post
- 网络请求,get和post
- Get和post网络请求
- 安卓网络--网络访问Post和Get
- 安卓HTTP请求之get和post方法。
- 安卓简单的POST和GET请求
- Spring mvc Controller 处理安卓post和get请求
- iOS 发送GET和POST网络请求
- Android-封装post和get 网络请求
- java网络请求GET和POST方式
- HttpURLConnection:POST和GET 网络请求
- swift3 AF网络post和get请求
- 网络请求(get&&post)
- 网络请求(get Post)
- HTTPRequest 网络请求之get请求和post请求
- 学习笔记之安卓GET与POST网络请求的三种方式
- eclipse中网络设置及get和post请求(get请求或者post请求)
- android网络请求之post和get请求方式
- Java 执行系统命令
- 浅谈电路设计中应用DDR3处理缓存问题
- 新博客地址
- 为什么我们要学习设计模式
- 使用Gson进行json处理
- 安卓网络请求只Get和Post
- 测试是是
- 【转】PostgreSQL 数据库在 Windows Server 2008 上安装注意事项
- OpenCV——Perlin Noise
- oracle rownum
- [WARN] Network error when fetching messages:storm-kafka-0.8导致kafka读取数据丢失
- 毕业四年后的总结和新的开始
- 【Java.Spring.Core】【IoC】Bean 作用域 - Scopes
- 士大夫撒地方