android网络编程(三)HttpURLConnection POST

效果图:
[img]
android网络编程(三)HttpURLConnection POST
[/img]


package com.amaker.http2;

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

import org.apache.http.protocol.HTTP;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
/**
 * HttpURLConnection
 * post
 * @author zzl
 *
 */
public class MainActivity extends Activity {
	private TextView tv;
	private Button btn_post;
	private String resultData = "";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		tv = (TextView) findViewById(R.id.tv);
		btn_post = (Button) findViewById(R.id.button);
		btn_post.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					tv.setText(requestByPost());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	public String requestByPost() throws Exception {
		String httpUrl = "http://open.ifenghui.cn/mobilecms/interface/mobile.action?";
		URL url = null;
		try {
			// 构造一个URL对象
			url = new URL(httpUrl);
		} catch (MalformedURLException e) {
			//    
		}
		if (url != null) {
			try {
				// 使用HttpURLConnection打开连接
				HttpURLConnection urlConn = (HttpURLConnection) url
						.openConnection();
				// 因为这个是post请求,设立需要设置为true
				urlConn.setDoOutput(true);
				urlConn.setDoInput(true);
				// 设置以POST方式
				urlConn.setRequestMethod("POST");
				// Post 请求不能使用缓存
				urlConn.setUseCaches(false);
				urlConn.setInstanceFollowRedirects(true);
				// 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
				urlConn.setRequestProperty("Content-Type",
						"application/x-www-form-urlencoded");
				// 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
				// 要注意的是connection.getOutputStream会隐含的进行connect。
				urlConn.connect();
				// DataOutputStream流
				DataOutputStream out = new DataOutputStream(urlConn
						.getOutputStream());
				// 要上传的参数:code=888032100100&m=get_coolimages&p=1&filter=all
				// 正文,正文内容其实跟get的URL中'?'后的参数字符串一致
				String content = "code=888032100100&m=get_coolimages&p=1&filter="
						+ URLEncoder.encode("all", "gb2312");
				// 将要上传的内容写入流中
				out.writeBytes(content);
				// 刷新、关闭
				out.flush();
				out.close();

				// 得到读取的内容(流)
				InputStreamReader in = new InputStreamReader(urlConn
						.getInputStream());
				// 为输出创建BufferedReader
				BufferedReader buffer = new BufferedReader(in);
				String inputLine = null;
				// 使用循环来读取获得的数据
				while (((inputLine = buffer.readLine()) != null)) {
					// 我们在每一行后面加上一个"\n"来换行
					resultData += inputLine + "\n";
				}
				// 关闭InputStreamReader
				in.close();
				return resultData;
			} catch (MalformedURLException e) {
				//
			}
		}
		return null;
	}

}


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent">
	<ScrollView
		android:id="@+id/sv"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		xmlns:android="http://schemas.android.com/apk/res/android"
		android:layout_x="0px"
		android:layout_y="20px">
		<TextView
			android:layout_width="fill_parent"
			android:layout_height="wrap_content"
			android:id="@+id/tv"
			android:text="@string/hello" />
	</ScrollView>
	<Button
		android:text="HttpURLConnection-POST请求"
		android:id="@+id/button"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content" />
</LinearLayout>



 



AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.amaker.http2"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="10" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <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>
    <!--不要忘记设置网络访问权限-->
    <uses-permission android:name="android.permission.INTERNET"></uses-permission> 
</manifest>

你可能感兴趣的:(http)