Android 使用URLConnection提交请求

来源:互联网 发布:最近流行搞怪拍照软件 编辑:程序博客网 时间:2024/06/06 01:05

这里写图片描述

URL相关的类:

URL;URLClassLoader;URLConnection;URLDecoder;URLEncoder;URLStreamHandler;URLStreamHandlerFactory;URLSpan;URLUtil;

GET POST:

GetPostUtils.java

package shortcut.song.com.myapplication;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.URL;import java.net.URLConnection;import java.util.List;import java.util.Map;/** * Created by Administrator on 2017/8/21 0021. */public class GetPostUtils {    /**     * 向指定URL 发送GET方式的请求     * @param url 发送请求的URL     * @param params 请求参数,请求参数应该是name1=value1&name2=value2的形式     * @return URL所代表的远程资源的响应     */    public static String sendGet(String url, String params) {        String result = "";        BufferedReader in = null;        try {            String urlName = url + "?"+params;            URL realUrl = new URL(urlName);            // 打开和URL之前对应的连接            URLConnection conn =  realUrl.openConnection();            // 设置通用的请求属性            conn.setRequestProperty("accept", "*/*");            conn.setRequestProperty("connection", "Keep-Alive");            conn.setRequestProperty("user-agent",                    "Mozilla/4.0 (compatible; MSIE 6.0; Windos NT 5.1; SV1)");            // 建立实际连接            conn.connect();            // 获取所有的响应头字段            Map<String, List<String>> map = conn.getHeaderFields();            // 遍历所有的响应头字段            for (String key: map.keySet()) {                System.out.println(key +"--->"+ map.get(key));            }            // 定义BufferedReader 输入流来读取URL的响应            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));            String line;            while((line = in.readLine()) != null){                result += "\n"+line;            }        } catch (Exception e) {            System.out.println("SendGET Exception!!!");            e.printStackTrace();        }        finally {            try {                if (in != null) {                    in.close();                }            }catch (IOException e) {                e.printStackTrace();            }        }        return result;    }    /**     *     * @param url     * @param params     * @return     */    public static String sendPost(String url, String params) {        String result="";        PrintWriter out = null;        BufferedReader in = null;        try {            URL realUrl = new URL(url);            // 打开和URL之间的连接            URLConnection conn = realUrl.openConnection();            // 设置通用的请求属性            conn.setRequestProperty("accept", "*/*");            conn.setRequestProperty("connection", "Keep-Alive");            conn.setRequestProperty("user-agent",                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");            // 发送POST请求必须设置如下两行            conn.setDoOutput(true);            conn.setDoInput(true);            // 获取URLConnection对象对应的输出流            out = new PrintWriter(conn.getOutputStream());            // 发送请求参数            out.print(params);            // flush输出缓冲            out.flush();            // 定义BufferedReader输入流来读取URL的响应            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));            String line;            while((line = in.readLine()) != null) {                result += "\n" + line;            }        } catch (Exception e){            System.out.println("Send POST Error!");            e.printStackTrace();        }        finally {            try {                if (out != null) {                    out.close();                }                if (in != null) {                    in.close();                }            }catch (IOException ex) {                ex.printStackTrace();            }        }        return result;    }}

AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context="shortcut.song.com.myapplication.URLConnectionActivity">    <Button        android:id="@+id/btn_get"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="get"/>    <Button        android:id="@+id/btn_post"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="post"/>    <TextView        android:id="@+id/edt_show"        android:layout_width="match_parent"        android:layout_height="wrap_content" /></LinearLayout>
package shortcut.song.com.myapplication;import android.os.Handler;import android.os.Message;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;public class URLConnectionActivity extends AppCompatActivity {    Button get;    Button post;    TextView textView;    String response;    Handler mHandler = new Handler() {        @Override        public void handleMessage(Message msg) {            super.handleMessage(msg);            if (msg.what == 0x123) {                textView.setText(response);            }        }    };    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_urlconnection);        get = (Button)findViewById(R.id.btn_get);        post = (Button)findViewById(R.id.btn_post);        textView = (TextView)findViewById(R.id.text_show);        get.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                new Thread(){                    @Override                    public void run() {                        super.run();                        response = GetPostUtils.sendGet("http://192.168.8.27/index.jsp", null);                        mHandler.sendEmptyMessage(0x123);                    }                }.start();            }        });        post.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                new Thread(){                    @Override                    public void run() {                        super.run();                        response = GetPostUtils.sendPost("http://192.168.8.27/index.jsp", "name=song&passwd=123");                    }                }.start();                mHandler.sendEmptyMessage(0x123);            }        });    }}
原创粉丝点击