关于 GET 和 POST 请求的简单示例

MainActivity.java :

package com.android.urinet;

import com.android.urigetpost.LoginNet;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

@SuppressLint("ShowToast")
public class MainActivity extends Activity {
	
	EditText edit1, edit2;
	Button bt1, bt2;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		edit1 = (EditText)findViewById(R.id.edit1);
		edit2 = (EditText)findViewById(R.id.edit2);
		bt1 = (Button)findViewById(R.id.bt1);
		bt2 = (Button)findViewById(R.id.bt2);
		
		bt1.setOnClickListener(new OnClickListener() {
			// GET
			@Override
			public void onClick(View v) {
				final String username = edit1.getText().toString();
				final String password = edit2.getText().toString();
				
				new Thread(new Runnable() {
					@Override
					public void run() {
					
						final String str = LoginNet.GetToNet(
								username,
								password, 
								"http://10.0.2.2:8080/baidu/TestServlet");
						
						runOnUiThread(new Runnable() {
							
							@Override
							public void run() {
								
								Toast.makeText(
										MainActivity.this, 
										"返回的状态为:" + str, 
										0).show();
							}
						});
					}
				}).start();
			}
		});
		
		
		bt2.setOnClickListener(new OnClickListener() {
			// POST
			@Override
			public void onClick(View v) {
				final String username = edit1.getText().toString();
				final String password = edit2.getText().toString();
				
				new Thread(new Runnable() {
					@Override
					public void run() {
					
						final String str = LoginNet.PostToNet(
								username,
								password, 
								"http://10.0.2.2:8080/baidu/TestServlet");
						
						runOnUiThread(new Runnable() {
							
							@Override
							public void run() {
								
								Toast.makeText(
										MainActivity.this, 
										"返回的状态为:" + str, 
										0).show();
							}
						});
					}
				}).start();
			}
		});
	}
	
}

链接网络的类:

LoginNet.java :

package com.android.urigetpost;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class LoginNet {
	/**
	 * 用 GET 方法登陆(先登录在传参数)
	 * @param username 用户名
	 * @param password 用户密码
	 * @param uri 
	 * @return
	 */
	public static String GetToNet(String username, String password, String uri){
		
		uri = uri + "?username=" + username + "&password=" + password;
		
		HttpURLConnection conn = FromNet(uri);
		
		try {
			conn.setConnectTimeout(30000);
			conn.setReadTimeout(30000);
			conn.setDoInput(true);
			
			conn.setRequestMethod("GET");
			
			conn.connect();
			
			if(conn.getResponseCode() == 200){
				
				InputStream is = conn.getInputStream();
				String content = getStringFromInputStream(is);
				
				return content;
			}
			
		} catch (ProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	
	/**
	 * 
	 * @param is 为 conn 调用 getInputStream() 时返回的对象
	 * @return 把返回的流转换为字符串
	 */
	private static String getStringFromInputStream(InputStream is) {
		
		byte[] buffer = new byte[1024];
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		
		
		try {
			while((is.read(buffer, 0, buffer.length)) != -1){
				baos.write(buffer);
			}
			
			return baos.toString();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}

	
	/**
	 * 先传参数再登陆
	 * @param username
	 * @param password
	 * @param uri
	 * @return
	 */
	public static String PostToNet(String username, String password, String uri){
		
		HttpURLConnection conn = FromNet(uri);
		
		try {
			conn.setConnectTimeout(30000);
			conn.setReadTimeout(30000);
			conn.setDoInput(true);
			
			conn.setRequestMethod("POST");
			
			OutputStream os = conn.getOutputStream();
			
			conn.connect();
			
			os.write(("username="+username + "&password=" + password).getBytes());
		
			if (conn.getResponseCode() == 200){
				
				String content = getStringFromInputStream(conn.getInputStream());
				
				return content;
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	
	/**
	 * 获取 HttpURLConnection 的链接,并返回其对象
	 * @param uri 从前文传入参数
	 * @return conn
	 */
	public static HttpURLConnection FromNet(String uri){
		
		try {
			URL url = new URL(uri);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	
			return conn;
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}
}

layout_main.xml :

<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="com.android.urinet.MainActivity" >

    <EditText
        android:id="@+id/edit1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/text1"
        android:singleLine="true"
        android:textSize="10pt"
        android:background="@drawable/bg_border"/>
    
    <EditText 
        android:id="@+id/edit2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/edit1"
        android:hint="@string/text2"
        android:singleLine="true"
        android:textSize="10pt"
        android:background="@drawable/bg_border"
        android:layout_marginTop="5dp"/>
    
    <Button 
        android:id="@+id/bt1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/edit2"
        android:textSize="10pt"
        android:text="@string/text3"
        android:layout_marginTop="5dp"/>
    
    <Button 
        android:id="@+id/bt2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/bt1"
        android:textSize="10pt"
        android:text="@string/text4"
        android:layout_marginTop="5dp"/>

</RelativeLayout>

还要在 AndroidManifest.xml 中注册权限:

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


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值