HttpURLconnection/get和post请求

来源:互联网 发布:zblog php主题 授权 编辑:程序博客网 时间:2024/05/17 03:17
package com.example.lenovo.getpost;


import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;


import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;


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


public class MainActivity extends AppCompatActivity {
    private String getpath = "http://v.juhe.cn/expressonline/getCarriers.php?key=6e5a5144e51a2cdb984bc81528562eab";
    private String getname = "GET";
    private String postpath = "http://v.juhe.cn/expressonline/getCarriers.php";
    private String postname = "POST";
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn_get = (Button) findViewById(R.id.btn_get);
        Button btn_post = (Button) findViewById(R.id.btn_post);


        //get提交
        btn_get.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        getData();
                    }
                }).start();


            }




        });
        //post提交
        btn_post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
             new Thread(new Runnable() {
                 @Override
                 public void run() {
                     postData();
                 }
             }).start();
            }
        });
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }


    /**
     * post提交
     */




    private void postData() {




        try {
            URL url = new URL(postpath);
            String pars="key=6e5a5144e51a2cdb984bc81528562eab&dtype=json";
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod(postname);
            connection.connect();
            DataOutputStream data=new DataOutputStream(connection.getOutputStream());
            data.writeBytes(pars);
            data.flush();
            data.close();


            int responseCode = connection.getResponseCode();
            if(responseCode==200)
            {
               InputStream ios=connection.getInputStream();
                BufferedReader buff=new BufferedReader(new InputStreamReader(ios));
                String line=null;
                final StringBuffer result=new  StringBuffer();
                while((line=buff.readLine())!=null)
                {
                    result.append(line);
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_SHORT).show();
                    }
                });


            }




        } catch (Exception e) {
            e.printStackTrace();
        }




    }


    /**
     * get提交
     */
    private void getData() {


        final StringBuffer result = new StringBuffer();
        try {
            URL url = new URL(getpath);
            //创建HttpURLConnection对象,用于连接请求和处理请求过程的相关数据
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();


            //获取连接方法
            connection.setRequestMethod(getname);
            //和服务器建立连接
            connection.connect();


            int responseCode = connection.getResponseCode();
            if (HttpURLConnection.HTTP_OK == responseCode) {    //客户端得到输入流
                InputStream ios = connection.getInputStream();
                //对输入流进行缓冲封装
                BufferedReader buff = new BufferedReader(new InputStreamReader(ios));
                String line = null;
                while ((line = buff.readLine()) != null) {
                    result.append(line);
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_SHORT).show();
                    }
                });
            } else {
                int errorCode1 = connection.getResponseCode();
                String errorMessage = connection.getResponseMessage();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onStart() {
        super.onStart();


        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Main Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://com.example.lenovo.getpost/http/host/path")
        );
        AppIndex.AppIndexApi.start(client, viewAction);
    }


    @Override
    public void onStop() {
        super.onStop();


        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Main Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://com.example.lenovo.getpost/http/host/path")
        );
        AppIndex.AppIndexApi.end(client, viewAction);
        client.disconnect();
    }
}

原创粉丝点击