HttpUrlConnection(POST方式)

这篇博客简要介绍了如何使用HttpUrlConnection在Android中进行POST请求。与GET请求的区别在于,POST请求用于向服务器提交数据,这些数据位于信息头后面。文章提供了相应的代码示例,并提到了该操作在子线程中执行。

上一篇大概步骤都讲了,这一片会写的很简略哦。
网上说GET和POST的区别是:GET是向服务器索取数据的一种请求,而POST是向服务器提交数据的一种请求,要提交的数据位于信息头后面。
代码如下:

  private class TwoThread implements Runnable {
        private OutputStream os;
        private InputStream is;
        private BufferedReader br;

        @Override
        public void run() {
            getPath();
            try {
                //将String类型的地址的封装为URL
                url = new URL(todayWeather);
                //打开服务器
                conn = (HttpURLConnection) url.openConnection();
                //设置请求方法为POST
                conn.setRequestMethod("POST");
                //POST方法不能缓存数据,则需要手动设置使用缓存的值为false
                conn.setUseCaches(false);
                //连接服务器
                conn.connect();
                /**写入参数*/
                os = conn.getOutputStream();
                //封装输出流
                DataOutputStream dos = new DataOutputStream(os);
                dos.writeBytes("name=" + URLEncoder.encode(edit.getText().toString()));
                dos.close();
                /**读取服务器数据*/
                is = conn.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                String line = null;
                StringBuffer sb = new StringBuffer();
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                sb.append("\n" + "\nWays:HttpUrlConnection-POST");
                content = sb.toString();
                Message message = new Message();
                message.what = 1;
                handler.sendEmptyMessage(message.what);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                    if (br!=null){
                        br.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }

又是子线程哦!!!
这个就是和上一篇唯一不同的地方了,我现在把源码贴出来自己看吧,因为好困,不想写了。

public class MainActivity extends Activity implements View.OnClickListener {

    private EditText edit;
    private Button one;
    private Button two;
    private Button three;
    private Button four;
    private TextView text;

    private String todayWeather;
    private Handler handler;

    //HttpUrlConnection方式所需成员变量
    private URL url;
    private HttpURLConnection conn;
    private String content;

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

        initView();

        one.setOnClickListener(this);
        two.setOnClickListener(this);
        three.setOnClickListener(this);
        four.setOnClickListener(this);

    }

    private void initView() {
        edit = (EditText) findViewById(R.id.edit);
        one = (Button) findViewById(R.id.one);
        two = (Button) findViewById(R.id.two);
        three = (Button) findViewById(R.id.three);
        four = (Button) findViewById(R.id.four);
        text = (TextView) findViewById(R.id.text);

        handler = new MyHandler();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.one:
                new Thread(new OneThread()).start();
                break;
            case R.id.two:
                //通过HttpUrlConnection的POST方式
                new Thread(new TwoThread()).start();
                break;
            case R.id.three:
                //通过HttpClient的GET方式
                new Thread(new ThreeThread()).start();
                break;
            case R.id.four:
                break;
            default:
                break;
        }
    }

    public void getPath() {
        String todayStart = "http://api.k780.com:88/?app=weather.today&weaid=";
        String todayCity = edit.getText().toString();
        String todayEnd = "&&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json";
        todayWeather = (todayStart + todayCity + todayEnd);
    }

    class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                text.setText(content);
            } else {
                text.setText("出错了");
            }
        }
    }


    private class OneThread implements Runnable {
        InputStream is;
        BufferedReader br;

        @Override
        public void run() {
            getPath();
            try {
                //通过路径得到URL对象
                url = new URL(todayWeather);
                //打开服务器
                conn = (HttpURLConnection) url.openConnection();
                //连接服务器
                conn.connect();
                //得到输入流
                is = conn.getInputStream();
                //封装
                br = new BufferedReader(new InputStreamReader(is));
                String line = null;
                //将数据存储在StringBuffere中
                StringBuffer sb = new StringBuffer();
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                sb.append("\n" + "\nWays:HttpUrlConnection-GET");
                content = sb.toString();
                Message message = new Message();
                message.what = 1;
                handler.sendEmptyMessage(message.what);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                    if (br != null) {
                        br.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    private class TwoThread implements Runnable {
        private OutputStream os;
        private InputStream is;
        private BufferedReader br;

        @Override
        public void run() {
            getPath();
            try {
                //将String类型的地址的封装为URL
                url = new URL(todayWeather);
                //打开服务器
                conn = (HttpURLConnection) url.openConnection();
                //设置请求方法为POST
                conn.setRequestMethod("POST");
                //POST方法不能缓存数据,则需要手动设置使用缓存的值为false
                conn.setUseCaches(false);
                //连接服务器
                conn.connect();
                /**写入参数*/
                os = conn.getOutputStream();
                //封装输出流
                DataOutputStream dos = new DataOutputStream(os);
                dos.writeBytes("name=" + URLEncoder.encode(edit.getText().toString()));
                dos.close();
                /**读取服务器数据*/
                is = conn.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                String line = null;
                StringBuffer sb = new StringBuffer();
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                sb.append("\n" + "\nWays:HttpUrlConnection-POST");
                content = sb.toString();
                Message message = new Message();
                message.what = 1;
                handler.sendEmptyMessage(message.what);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                    if (br!=null){
                        br.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }
}

one是表示点击使用HttpUrlConnection的GET方式的按钮;
two是表示点击使用HttpUrlConnection的POST方式的按钮;
three和four还没写呢,不要管。
好累,要去超市了,Bye!!!

### 回答1: HttpURLConnection 是 Java 的标准类库之一,可以用来发送 HTTP 请求。它支持 GET、POST、HEAD、OPTIONS、PUT、DELETE 和 TRACE 方法。可以使用 HttpURLConnection 类来发送 HTTP POST 请求。通常使用 HttpURLConnection 类发送 POST 请求时,需要设置请求头信息和请求参数。下面是一个示例代码: ``` URL url = new URL("http://www.example.com"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.connect(); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.writeBytes("param1=value1&param2=value2"); out.flush(); out.close(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String lines; StringBuffer sb = new StringBuffer(""); while ((lines = reader.readLine()) != null) { sb.append(lines); } System.out.println(sb.toString()); ``` 以上代码使用了 HttpURLConnection 发送一个 HTTP POST 请求,并设置了一些请求头信息(如 Content-Type)和请求参数。 注意:如果你在使用这个类发送请求时遇到了问题,请检查服务端是否支持该请求方法。 ### 回答2: HttpURLConnection Post是一种与服务器进行HTTP协议通信的方法。它是HttpURLConnection的子类,可以方便地发送POST请求并接收服务器响应。要使用HttpURLConnectionPOST方法,需要设置好URLConnection的请求属性,并根据需要写入请求正文数据,并接收返回的响应数据。 具体实现流程如下: 1. 创建HttpURLConnection连接对象,并设置请求的URL地址。 2. 通过setRequestMethod()方法设置POST方式。 3. 设置URLConnection的一些请求属性,如请求超时时间、接收数据超时时间等。 4. 如果需要向服务器发送请求正文数据,则需要在HttpURLConnection对象中开启输出流(setDoOutput(true))并写入正文数据(如表单参数、JSON参数等)。 5. 向服务器发送请求,调用HttpURLConnection的connect()方法。 6. 接收服务器返回的响应数据,可以通过getInputStream()方法读取响应数据。 7. 如果要读取服务器返回的响应状态码、响应头信息等,可以通过HttpURLConnection提供的方法来获取。 使用HttpURLConnection Post方法要注意以下几点: 1. POST请求发送的参数需要绑定在请求正文中,通过OutputStream将请求正文发送给服务器。 2. 如果需要向服务器发送一个文件,则可以使用multipart/form-data编码方式。 3. HttpsURLConnection是HttpURLConnection的子类,支持HTTPS请求。在发送HTTPS请求前需要配置SSLSocketFactory和HostnameVerifier。 总结来说,HttpURLConnection Post方法是一种比较简单易用的与服务器进行HTTP协议通信的方法,可以方便地发送POST请求并接收服务器响应。在实际开发中,如果要进行HTTP协议通信,建议选择使用HttpURLConnection Post方法。 ### 回答3: HttpURLConnectionAndroid 中的一个网络通信库,可以用来进行网络请求操作。其中,post 方法是 HttpURLConnection 中比较常用的一个方法。 post 方法的作用是向服务器提交数据。与 get 方法不同,post 方法不会将请求参数附加在 URL 中,而是将参数放在请求体中一并提交给服务器。这样设计的好处是可以避免 URL 过长,同时也可以保障数据的隐私性。 在使用 post 方法时,需要注意以下几个问题: 1. 设置请求方法:在创建 HttpURLConnection 对象之后,需要使用 setRequestMethod("POST") 方法将请求方法设置为 POST。 2. 设置请求头:在发送 post 请求之前,需要设置请求头,其中至少包含 Content-Type 和 Content-Length。Content-Type 指明请求体内容类型,微信支付时必须设置为 application/json。Content-Length 则指明请求体内容长度。 3. 设置请求体:用 OutputStream 向请求中写入需要提交的数据。 下面是一个 post 方法的示例代码: ``` URL url = new URL("http://example.com/api"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Content-Length", String.valueOf(postData.length())); OutputStream os = conn.getOutputStream(); os.write(postData.getBytes(StandardCharsets.UTF_8)); os.flush(); os.close(); int responseCode = conn.getResponseCode(); ``` 其中,url 表示请求的地址,postData 是需要提交的数据。 上述代码中,创建 HttpURLConnection 对象之后,我们首先使用 setRequestMethod 方法将请求方法设置为 POST,然后设置了两个请求头,最后将请求体写入到 outputstream 中。 执行完 write 方法之后,需要调用 flush 方法和 close 方法。其中 flush 方法是为了清空 buffer 缓存,将数据真正发送出去,close 方法是为了关闭输出流。 最后,使用 getResponseCode 方法获取服务器返回的状态码。根据不同的状态码,进行相应的处理即可。 总的来说,HttpURLConnection 中的 post 方法十分简单,只需要注意请求头和请求体的设置即可。在实际开发中,post 方法通常用于向服务器提交表单数据、文件上传、支付等一系列操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值