关闭

android_30_使用HttpClient发送Get和Post请求

标签: androidHttpClientGETPOST
99人阅读 评论(0) 收藏 举报
分类:

效果:


清单:(权限)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sg31.httpclient"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    // 注意权限 
    <uses-permission android:name="android.permission.INTERNET"/>
    <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>


布局:

<LinearLayout 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="com.sg31.httpclient.MainActivity" 
    android:orientation="vertical"
    >

    <EditText
        android:id="@+id/et_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入意见或建议" 
        android:text="啊,发现一个大Bug!!!"
        />
    <EditText
        android:id="@+id/et_contact"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请留下妳的联系方式(可空)" 
        />
    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="getBtnClicked"
        android:text="GET方式提交"
        />
    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="postBtnClicked"
        android:text="POST方式提交"
        />

    <ScrollView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        >
    <TextView 
        android:id="@+id/tv_response"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</ScrollView>

</LinearLayout>


帮助类:

package com.sg31.httpclient;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

public class TextHelper {

public static String textFromStream(InputStream is){
        
        byte[] b = new byte[1024];
        int len = 0;
        //创建字节数组输出流,读取输入流的文本数据时,同步把数据写入数组输出流
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            while((len = is.read(b)) != -1){
                bos.write(b, 0, len);
            }
            //把字节数组输出流里的数据转换成字节数组
            String text = new String(bos.toByteArray());
            return text;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}


主控制器:

package com.sg31.httpclient;

import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
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 android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

	Handler handler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			Toast.makeText(MainActivity.this, (String) msg.obj, 0).show();
			
			TextView tv_response = (TextView) findViewById(R.id.tv_response);
			tv_response.setText((String) msg.obj);
			
			
			
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	@Override
	public 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;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	public void getBtnClicked(View v) {
		EditText et_content = (EditText) findViewById(R.id.et_content);
		EditText et_contact = (EditText) findViewById(R.id.et_contact);

		final String content = et_content.getText().toString();
		final String contact = et_contact.getText().toString();

		Thread t = new Thread() {
			@Override
			public void run() {
				String path = "http://sg31.com/ci/androidfeedback/insertwithget?language=android&content="
						+ URLEncoder.encode(content) + "&contact=" + contact;
				// 使用httpClient框架做get方式提交
				// 1.创建HttpClient对象
				HttpClient hc = new DefaultHttpClient();

				// 2.创建httpGet对象,构造方法的参数就是网址
				HttpGet hg = new HttpGet(path);

				// 3.使用客户端对象,把get请求对象发送出去
				try {
					HttpResponse hr = hc.execute(hg);
					// 拿到响应头中的状态行
					StatusLine sl = hr.getStatusLine();
					System.out.println("sg__"+sl.getStatusCode());
					if (sl.getStatusCode() == 200) {
						// 拿到响应头的实体
						HttpEntity he = hr.getEntity();
						// 拿到实体中的内容,其实就是服务器返回的输入流
						InputStream is = he.getContent();
						String text = TextHelper.textFromStream(is);

						// 发送消息,让主线程刷新ui显示text
						Message msg = handler.obtainMessage();
						msg.obj = text;
						handler.sendMessage(msg);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		t.start();

	}

	public void postBtnClicked(View v) {
		EditText et_content = (EditText) findViewById(R.id.et_content);
		EditText et_contact = (EditText) findViewById(R.id.et_contact);

		final String content = et_content.getText().toString();
		final String contact = et_contact.getText().toString();

		Thread t = new Thread() {
			@Override
			public void run() {
				String path = "http://sg31.com/ci/androidfeedback/insertwithpost";
				// 1.创建客户端对象
				HttpClient hc = new DefaultHttpClient();
				// 2.创建post请求对象
				HttpPost hp = new HttpPost(path);

				// 封装form表单提交的数据
				BasicNameValuePair bnvp = new BasicNameValuePair("language", "android");
				BasicNameValuePair bnvp1 = new BasicNameValuePair("content", content);
				BasicNameValuePair bnvp2 = new BasicNameValuePair("contact", contact);
				List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
				// 把BasicNameValuePair放入集合中
				parameters.add(bnvp);
				parameters.add(bnvp1);
				parameters.add(bnvp2);

				try {
					// 要提交的数据都已经在集合中了,把集合传给实体对象
					UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
							parameters, "utf-8");
					// 设置post请求对象的实体,其实就是把要提交的数据封装至post请求的输出流中
					hp.setEntity(entity);
					// 3.使用客户端发送post请求
					HttpResponse hr = hc.execute(hp);
					if (hr.getStatusLine().getStatusCode() == 200) {
						InputStream is = hr.getEntity().getContent();
						String text = TextHelper.textFromStream(is);

						// 发送消息,让主线程刷新ui显示text
						Message msg = handler.obtainMessage();
						msg.obj = text;
						handler.sendMessage(msg);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		t.start();

	}

}





附PHP代码:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
// header("Content-Type: text/html; charset=utf-8");
class Androidfeedback extends CI_Controller {


// 录入到where表格中,并且返回另一半的地址
    public function insertwithpost(){
        
        $language = $_POST["language"];
        echo "language";
        $content = $_POST["content"];
        echo "content";
        // 可空
        $contact = $_POST["contact"];
        echo "contact";
        $ipaddress = $_SERVER["REMOTE_ADDR"];
        echo "ipaddress";
        $servername = $_SERVER['SERVER_NAME'];
        echo "servername";
        // if ($servername != "sg31.com") {
        //     # code...
        //     echo "非法的访问";
        //     return;
        // }
         // 时间戳
        $timeStamp = time();
        if (strlen($content) > 250 || strlen($contact) > 250 || strlen($language) > 250) {
            # code...
            echo "字数不得超过255";
            return;
        }
        if (strlen($content) == 0 || strlen($language) == 0) {
            # code...
            echo "妳还没有输入内容";
            return;
        }
        if (strlen($contact) == 0) {
            # code...
            $contact = "sg31.com";
        }

            // 成功则插入,返回ok
            // 插入 (REMOTE_ADDR)
        // 时间戳
        $pubtime = time();
        $pubdate = date("Y-m-d");
                $sql =
                'INSERT INTO sg_app_feedback(language,content,contact,pubtime,ipaddress,pubdate)
                VALUES(?,?,?,?,?,?)';
                
                // $sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?";
                
                $B = $this->db->query($sql, array($language,$content,$contact,$pubtime,$ipaddress,$pubdate));
                if ($B == 1) {
                    # code...
                    // 插入成功,返回ok
                    echo "<h1>We are glad to hear from you:".$ipaddress."--".$servername."!</h1><h1>Thanks for your suggestion!</h1><h1>Best wishes for you!</h1>";
                }

          
    }

    
    // 录入到where表格中,并且返回另一半的地址
    public function insertwithget(){
        
        $language = $_GET["language"];
        $content = $_GET["content"];
        // 可空
        $contact = $_GET["contact"];
        $ipaddress = $_SERVER["REMOTE_ADDR"];
        $servername = $_SERVER['SERVER_NAME'];
        // if ($servername != "sg31.com") {
        //     # code...
        //     echo "非法的访问";
        //     return;
        // }
         // 时间戳
        $timeStamp = time();
        if (strlen($content) > 250 || strlen($contact) > 250 || strlen($language) > 250) {
            # code...
            echo "字数不得超过255";
            return;
        }
        if (strlen($content) == 0 || strlen($language) == 0) {
            # code...
            echo "妳还没有输入内容";
            return;
        }
        if (strlen($contact) == 0) {
            # code...
            $contact = "sg31.com";
        }

            // 成功则插入,返回ok
            // 插入 (REMOTE_ADDR)
        // 时间戳
        $pubtime = time();
        $pubdate = date("Y-m-d");
                $sql =
                'INSERT INTO sg_app_feedback(language,content,contact,pubtime,ipaddress,pubdate)
                VALUES(?,?,?,?,?,?)';
                
                // $sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?";
                
                $B = $this->db->query($sql, array($language,$content,$contact,$pubtime,$ipaddress,$pubdate));
                if ($B == 1) {
                    # code...
                    // 插入成功,返回ok
                    echo "<h1>We are glad to hear from you:".$ipaddress."--".$servername."!</h1><h1>Thanks for your suggestion!</h1><h1>Best wishes for you!</h1>";
                }

          
    }








     
}

/* End of file log.php */
/* Location: ./application/controllers/log.php */






















0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:357411次
    • 积分:8337
    • 等级:
    • 排名:第2337名
    • 原创:472篇
    • 转载:2篇
    • 译文:0篇
    • 评论:74条
    最新评论