android 使用http get 与post 访问网络

布局文件activity_main.xml:

<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:gravity="center_horizontal"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <EditText android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <Button android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="发表"/>
    <ScrollView 
        android:id="@+id/scrollView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1">
        <LinearLayout 
            android:id="@+id/linearLayout1"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <TextView android:id="@+id/result"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"/>
        </LinearLayout>
    </ScrollView>
        

</LinearLayout>
主类:

MainActivity.java:

package com.example.dhttpget;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	
	private EditText content ;
	private Button button;
	private Handler handler;
	private String result="";
	private TextView resultTv;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		content = (EditText)findViewById(R.id.content);
		resultTv = (TextView)findViewById(R.id.result);
		button = (Button)findViewById(R.id.button);
		
		handler = new Handler(){
			public void handleMessage(Message msg){
				if(result!=null){
					resultTv.setText(result);
					content.setText("");
				}
				super.handleMessage(msg);
			}
		};
		
		button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View view) {
				// TODO Auto-generated method stub
//				if("".equals(content.getText().toString())){
//					Toast.makeText(MainActivity.this, "请输入要发表的内容!", Toast.LENGTH_LONG).show();
//					return;
//				}
				
				new Thread(new Runnable(){
					public void run(){
						send();
						Message m = handler.obtainMessage();
						handler.sendMessage(m);
					}
				}).start();
			}
		});
	}

	@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;
	}
	
	public void send(){
		String target = "http://www.baidu.com/";
		
		URL url;
		try{
			url = new URL(target);
			HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
			
			InputStreamReader in = new InputStreamReader(urlConnection.getInputStream());
			BufferedReader buffer = new BufferedReader(in);
			String inputLine = null;
			while((inputLine=buffer.readLine())!=null){
				result+=inputLine+"\n";
			}
			in.close();
			urlConnection.disconnect();
			
		}catch(MalformedURLException e){
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}
		
	}
	
	public String base64(String content){
		try {
			content = Base64.encodeToString(content.getBytes("utf-8"), Base64.DEFAULT);
			content = URLEncoder.encode(content);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return content;
	}

}

AndroidManifest.xml:

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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.dhttpget.PostActivity"
            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>
    
    <uses-permission android:name="android.permission.INTERNET"/>

</manifest>


以前代码是用http get 方法访问网络,

接下来,使用http post:

布局文件与上面类似。

具体主类PostActivity.java:

package com.example.dhttpget;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class PostActivity extends Activity {
	
	
	private EditText nickname;
	private EditText content ;
	private Button button;
	private Handler handler;
	private String result="";
	private TextView resultTv;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dhttp_post);
		
		content = (EditText)findViewById(R.id.content);
		resultTv = (TextView)findViewById(R.id.result);
		button = (Button)findViewById(R.id.button);
		
		handler = new Handler(){
			public void handleMessage(Message msg){
				if(result!=null){
					resultTv.setText(result);
					content.setText("");
				}
				super.handleMessage(msg);
			}
		};
		
		button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View view) {
				// TODO Auto-generated method stub
//				if("".equals(content.getText().toString())){
//					Toast.makeText(MainActivity.this, "请输入要发表的内容!", Toast.LENGTH_LONG).show();
//					return;
//				}
				
				new Thread(new Runnable(){
					public void run(){
						send();
						Message m = handler.obtainMessage();
						handler.sendMessage(m);
					}
				}).start();
			}
		});
		
		
	}

	
	public void send(){
		String targer = "http://www.baidu.com/";
		URL url;
		try {
			url = new URL(targer);
			HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
			urlConn.setRequestMethod("POST");
			urlConn.setDoOutput(true);
			urlConn.setUseCaches(true);
			urlConn.setInstanceFollowRedirects(true);
			urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			
			DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());
			String param = "";
			
			out.writeBytes(param);
			out.flush();
			out.close();
			
			if(urlConn.getResponseCode()==HttpURLConnection.HTTP_OK){
				InputStreamReader in = new InputStreamReader(urlConn.getInputStream());
				
				BufferedReader buffer = new BufferedReader(in);
				String inputLine = null;
				while((inputLine=buffer.readLine())!=null){
					result += inputLine + "\n";
				}
				in.close();
			}
			
			urlConn.disconnect();
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}


转载于:https://my.oschina.net/u/2552902/blog/543822

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值