HttpUrlConnection的post方式用法

17 篇文章 0 订阅

post方式在连接时候,要通过流吧参数传到服务器。

接收到返回的输入流时候,处理方式和get一致。

<pre name="code" class="java">package com.example.dugaolong.httpurlconnectiondemo;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

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

/**
 * Created by dugaolong on 16/5/16.
 */
public class Postactivity extends Activity {

    private static final String TAG = Postactivity.class.getSimpleName();

    private TextView textView;
    private Handler mHandler;

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

        //在ui线程中定义handler
        mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 1){
                    textView.setText(msg.obj.toString());
                }
            }

        };
        Button button = (Button) findViewById(R.id.bt_post);
        textView = (TextView) findViewById(R.id.tv_message);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                postHttpUrlConnection();
            }
        });
    }
    /**
     * post方式请求网络
     */
    private void postHttpUrlConnection() {
        //post的url路径不用加参数
        final String postUrl = "http://172.16.150.71:8080/http/servlet/Http";
        //请求网络必须要开新的子线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(postUrl);//URL对象
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();//使用URL打开一个链接
                    conn.setReadTimeout(5 * 1000);//
                    conn.setConnectTimeout(5 * 1000);//连接超时
                    conn.setRequestMethod("POST");// Set the post method. Default is GET
                    conn.setUseCaches(false);// Post 请求不能使用缓存
                    //设置请求头信息
                    conn.setRequestProperty("Connection", "Keep-Alive");//保持连接
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//设置请求体的类型是文本类型
                    // 发送POST请求必须设置如下两行
                    conn.setDoOutput(true);//设置是否向connection输出
                    conn.setDoInput(true);//Read from the connection. Default is true.
//                    conn.connect();

                    //要注意的是connection.getOutputStream会隐含的进行connect。
                    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                    String params="sex=girl";设置传递的参数(表单参数与get形式一样)
                    String encoding="UTF-8";
                    byte[] data = params.getBytes(encoding);

                    //DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面
                    out.write(data);
                    out.flush();
                    out.close(); // flush and close
                    /****************************请求完成**********************************/

                    //接收返回结果
                    if (conn.getResponseCode() == 200) {
                        //读取返回的流信息
                        InputStream is = conn.getInputStream();
                        BufferedReader br = new BufferedReader(new InputStreamReader(is));
                        StringBuffer sb = new StringBuffer();
                        String readLine = "";
                        while ((readLine = br.readLine()) != null) {//一行一行读取
                            sb.append(readLine);
                        }
                        //关闭流
                        is.close();
                        br.close();
                        conn.disconnect();
                        Message msg = new Message();
                        msg.what=1;
                        msg.obj=sb.toString();
                        mHandler.sendMessage(msg);
                        Log.i(TAG, "reaponse:" + sb.toString());
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

 

 layout_post.xml文件 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:id="@+id/bt_post"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="doPost"/>


    <TextView
        android:id="@+id/tv_message"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值