1. 程式人生 > >HTTP操作(GET,POST),執行緒的使用,介面的切換

HTTP操作(GET,POST),執行緒的使用,介面的切換

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.http"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".http"
            android:label="@string/title_activity_http" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".GET"
            android:label="@string/title_activity_get" >
            <intent-filter>
                <action android:name="android.intent.action.get" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".POST"
            android:label="@string/title_activity_post" >
            <intent-filter>
                <action android:name="android.intent.action.post" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
<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" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="40dp"
        android:onClick="jumpToGet"
        android:text="GET" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/button1"
        android:layout_marginTop="40dp"
        android:onClick="jumpToPost"
        android:text="POST" />
    
</RelativeLayout>

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" >

    <TextView
        android:id="@+id/gettextView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="URL:"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/geteditText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/gettextView1"
        android:ems="10"
        android:inputType="textNoSuggestions"
        android:text="http://btbu.pw/test.php" >

    </EditText>

    <Button
        android:id="@+id/getbutton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignRight="@+id/geteditText1"
        android:layout_below="@+id/geteditText1"
        android:onClick="get"
        android:text="GET" />


    <TextView
        android:id="@+id/gettextView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/getbutton1"
        android:text="TextView" />

</RelativeLayout>
GET
<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" >

    <TextView
        android:id="@+id/ptextView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:text="URL:"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/peditText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/pbutton1"
        android:ems="10"
        android:inputType="textNoSuggestions"
        android:text="http://btbu.pw/test.php" />

    <EditText
        android:id="@+id/peditText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/peditText1"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/peditText1"
        android:ems="10"
        android:inputType="textNoSuggestions"
        android:text="name=ypw&data=test1234" />

    <Button
        android:id="@+id/pbutton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/peditText1"
        android:onClick="post"
        android:text="POST" />

    <TextView
        android:id="@+id/ptextView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/pbutton1"
        android:text="textView2" />

</RelativeLayout>
POST
package com.example.http;

import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;

public class http extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http);
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
        .detectDiskWrites()
        .detectDiskReads()
        .detectNetwork()
        .penaltyLog()
        .build());
        
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
        .detectLeakedSqlLiteObjects()
        .detectLeakedClosableObjects()
        .penaltyLog()
        .penaltyDeath()
        .build());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //getMenuInflater().inflate(R.menu.activity_http, menu);
        return true;
    }
    
    public void jumpToGet(View v){
    	Intent intent = new Intent();
    	intent.setClass(this, GET.class);
    	startActivity(intent);
    }
    public void jumpToPost(View v){
    	Intent intent = new Intent();
    	intent.setClass(this, POST.class);
    	startActivity(intent);
    }    
}

HTTP

package com.example.http;

import java.io.*;

import org.apache.http.*;
import org.apache.http.client.*;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.*;
import org.apache.http.util.EntityUtils;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.*;
import android.os.*;

public class GET extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_get);

        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
        .detectDiskWrites()
        .detectDiskReads()
        .detectNetwork()
        .penaltyLog()
        .build());
        
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
        .detectLeakedSqlLiteObjects()
        .detectLeakedClosableObjects()
        .penaltyLog()
        .penaltyDeath()
        .build());    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //getMenuInflater().inflate(R.menu.activity_get, menu);
        return true;
    }
    
    public String HTTPGET(String url)
    {
    	String result = "";
    	try{
    		HttpGet httpget=new HttpGet(url);
    		HttpClient httpclient = new DefaultHttpClient();
    		HttpResponse hResponse;
    		hResponse = httpclient.execute(httpget);
    		if(hResponse.getStatusLine().getStatusCode()==200)
    			{
    				result = EntityUtils.toString(hResponse.getEntity());
    			}

    	}catch (ClientProtocolException e){
    		e.printStackTrace();
    	}catch (IOException e){
    		e.printStackTrace();
    	}
    	return(result);
    }
    
    Runnable get = new Runnable(){
		@Override
    	public void run(){
    		final EditText editText1 =(EditText)findViewById(R.id.geteditText1);
	    	final TextView textView2 =(TextView)findViewById(R.id.gettextView2);
	    	final String url = editText1.getText().toString();
	    	final String result = HTTPGET(url);
	    	textView2.post(new Runnable() {
                public void run() {
                	textView2.setText(result);
                }
            });
    	}
    };

    public void get(View v)
    {
    	Thread thread = new Thread(get);
    	thread.start();
    }
}

GET
package com.example.http;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.*;
import org.apache.http.client.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.*;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.*;

public class POST extends Activity {

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post);

        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
        .detectDiskWrites()
        .detectDiskReads()
        .detectNetwork()
        .penaltyLog()
        .build());
        
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
        .detectLeakedSqlLiteObjects()
        .detectLeakedClosableObjects()
        .penaltyLog()
        .penaltyDeath()
        .build());    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //getMenuInflater().inflate(R.menu.activity_get, menu);
        return true;
    }
    
    public String HTTPPOST(String url,String postdata)
    {
    	String result = "";
    	HttpPost hPost=new HttpPost(url);
    	List <NameValuePair> params=new ArrayList<NameValuePair>();
    	String posts[]=postdata.split("&");
    	String posts2[];
    	int i;
		for(i=0;i<posts.length;i++)
		{
			posts2=posts[i].split("=");
			params.add(new BasicNameValuePair (posts2[0],posts2[1]));
		}
    	try{
    		HttpEntity hen=new UrlEncodedFormEntity(params,"gb2312");
    		hPost.setEntity(hen);
    		HttpClient httpclient = new DefaultHttpClient();
    		HttpResponse hResponse;
    		hResponse = httpclient.execute(hPost);
    		if(hResponse.getStatusLine().getStatusCode()==200)
    			{
    				result = EntityUtils.toString(hResponse.getEntity());
    				result = new String(result.getBytes("ISO_8859_1"),"gbk");
    			}

    	}catch (Exception e){
    		e.printStackTrace();
    	}
    	return(result);
    }
    
    Runnable post = new Runnable(){
		@Override
    	public void run(){
    		EditText editText1 =(EditText)findViewById(R.id.peditText1);
    		EditText editText2 =(EditText)findViewById(R.id.peditText2);
	    	final TextView textView2 =(TextView)findViewById(R.id.ptextView2);
	    	String url = editText1.getText().toString();
	    	String postdata = editText2.getText().toString();
	    	final String result = HTTPPOST(url,postdata);
	    	textView2.post(new Runnable() {
                public void run() {
                	textView2.setText(result);
                }
            });
    	}
    };

    public void post(View v)
    {
    	Thread thread = new Thread(post);
    	thread.start();
    }
}

POST