HttpUrlConnection用get和post请求发送参数

post请求:

  final String nameValue = username.getText().toString();
    final String passValue = password.getText().toString();
            new Thread(){
                public void run() {
                    try {
                        URL url = new URL(login_url);
                        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
                        urlConn.setConnectTimeout(5*1000);//设置连接时间为5秒
                        urlConn.setReadTimeout(5*1000);//设置读取时间为5秒
                        urlConn.setRequestMethod("POST");//设置请求方式为post
                        urlConn.setDoOutput(true);
                        urlConn.setDoInput(true);
                        //添加参数
                        OutputStream outputStream = urlConn.getOutputStream();
                        String data = "username="+nameValue+"&password="+passValue;//拼装参数
                        outputStream.write(data.getBytes());//上传参数
                        int code = urlConn.getResponseCode();
                        if(code == 200){//相应成功,获得相应的数据
                            InputStream is = urlConn.getInputStream();//得到数据流(输入流)

                            byte[] buffer = new byte[1024];
                            int length = 0;
                            String str = "";
                            while((length = is.read(buffer)) > -1){
                                str += new String(buffer,0,length);
                            }
                            Log.d("main", str);
                            //解析json,展示在ListView(GridView)
                            //h.sendMessage(h.obtainMessage(3, str));
                            LoginResult lr = new Gson().fromJson(str, LoginResult.class);
                            if(lr.getCode() == 1){
                                //可以本地保存服务器发送过来的完整的账号信息
                                User user = lr.getUser();//得到账号的完整信息(从服务器发送过来)
                                String header = user.getHeader();//得到头像url
                                Intent it = new Intent(MainActivity.this,SuccessActivity.class);
                                it.putExtra("headerUrl", header);
                                startActivity(it);
                            }else{
                                Toast.makeText(MainActivity.this, "登陆失败,请重新输入", 0).show();
                            }
                        }

                    } catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                };
            }.start();

get请求

login.setOnClickListener(new OnClickListener() {        
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            final String nameValue = username.getText().toString();
            final String passValue = password.getText().toString();
            //访问服务器
            new Thread(){
                public void run() {
                    //拼装url
                    //URLEncoder.encode对汉字进行编码,服务器进行解码设置,解决中文乱码
                    try {
                        String lastUrl = login_url + "?username="+URLEncoder.encode(nameValue, "utf-8")+"&password="+passValue;
                        URL url = new URL(lastUrl);
                        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();//开发访问此连接
                        //设置访问时长和相应时长
                        urlConn.setConnectTimeout(5*1000);//设置连接时间为5秒
                        urlConn.setReadTimeout(5*1000);//设置读取时间为5秒
                        int code = urlConn.getResponseCode();//获得相应码
                        if(code == 200){//相应成功,获得相应的数据
                            InputStream is = urlConn.getInputStream();//得到数据流(输入流)
                            byte[] buffer = new byte[1024];
                            int length = 0;
                            String data = "";
                            while((length = is.read(buffer)) != -1){
                                String str = new String(buffer,0,length);
                                data += str;
                            }

                            Log.d("main", data);
                            //解析json,展示在ListView(GridView)
                            h.sendMessage(h.obtainMessage(2, data));


                        }

                    } catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                };
            }.start();
        };
    });
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是使用 Java 代码编写 HttpURLConnection 发送 GET 和 POST 请求的示例: 1. 发送 GET 请求 ```java import java.net.*; import java.io.*; public class HttpGet { public static void main(String[] args) { try { URL url = new URL("http://example.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ``` 2. 发送 POST 请求 ```java import java.net.*; import java.io.*; public class HttpPost { public static void main(String[] args) { try { URL url = new URL("http://example.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/json"); conn.setDoOutput(true); String input = "{\"username\":\"test\",\"password\":\"test\"}"; OutputStream os = conn.getOutputStream(); os.write(input.getBytes()); os.flush(); if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ``` 注意,在发送 POST 请求时需要设置 `Content-Type` 和向输出流中写入请求体。如果需要发送其他类型的请求,可以根据需要修改 `setRequestMethod` 和请求头部。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值