Volley的GET和POST方法

首先记得加上权限

<uses-permission android:name="android.permission.INTERNET"/>

XML代码

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.dell.fuwuqicunchu.fuwuqicunchu"
    android:orientation="vertical">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:id="@+id/et_1"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="volleyget"
            android:onClick="volleyget"
            android:layout_weight="1"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="volleypost"
            android:onClick="volleypost"
            android:layout_weight="1"/>
    </LinearLayout>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/et_2"/>
</LinearLayout>

JAVA代码

package com.example.dell.myfuwuqi;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.util.HashMap;
import java.util.Map;

public class webActivity extends AppCompatActivity {

    EditText et_1;
    EditText et_2;

    RequestQueue requestQueue;

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

        et_1=(EditText)findViewById(R.id.et_1);
        et_1.setText("http://192.168.1.101:8080/Testweb/testweb.jsp");
        et_2=(EditText)findViewById(R.id.et_2);

        requestQueue =Volley.newRequestQueue(this);

    }

    public void volleyget(View view)
    {
        final ProgressDialog progressDialog = new ProgressDialog(this);

        StringRequest str = new StringRequest(et_1.getText().toString(), new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {

                et_2.setText(s);

                progressDialog.dismiss();

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(webActivity.this, "失败", Toast.LENGTH_SHORT).show();
                progressDialog.dismiss();
            }
        });

        requestQueue.add(str);

    }



    public void volleypost(View v)
    {
        final ProgressDialog dialog = new ProgressDialog(this);

        StringRequest str = new StringRequest(Request.Method.POST, et_1.getText().toString(), new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {

                et_2.setText(s);

                dialog.dismiss();

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

                Toast.makeText(webActivity.this, "失败", Toast.LENGTH_SHORT).show();
                dialog.dismiss();
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<String,String>();

                map.put("name","volley");
                return map;
            }
        };

        requestQueue.add(str);
    }
}

 

转载于:https://www.cnblogs.com/youshashuosha/p/5419201.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在 Android 中进行 JSON 的 POST 和 GET 请求,可以使用 Android 所提供的 HttpUrlConnection 类或者 Volley 框架,以下分别介绍两种方法: 1. 使用 HttpUrlConnection 进行 POST 和 GET 请求: - POST 请求: ```java URL url = new URL("http://example.com/api"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); conn.setRequestProperty("Accept", "application/json"); conn.setDoOutput(true); conn.setDoInput(true); JSONObject jsonParam = new JSONObject(); jsonParam.put("param1", "value1"); jsonParam.put("param2", "value2"); DataOutputStream os = new DataOutputStream(conn.getOutputStream()); os.writeBytes(jsonParam.toString()); os.flush(); os.close(); int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader in = new BufferedReader(new InputStreamReader( conn.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // Handle response } else { // Error handling } ``` - GET 请求: ```java URL url = new URL("http://example.com/api?param1=value1&param2=value2"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); conn.setRequestProperty("Accept", "application/json"); int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader in = new BufferedReader(new InputStreamReader( conn.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // Handle response } else { // Error handling } ``` 2. 使用 Volley 进行 POST 和 GET 请求: - POST 请求: ```java String url = "http://example.com/api"; JSONObject jsonParam = new JSONObject(); jsonParam.put("param1", "value1"); jsonParam.put("param2", "value2"); JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, jsonParam, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { // Handle response } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // Error handling } }); request.setRetryPolicy(new DefaultRetryPolicy( 5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); RequestQueue queue = Volley.newRequestQueue(context); queue.add(request); ``` - GET 请求: ```java String url = "http://example.com/api?param1=value1&param2=value2"; JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { // Handle response } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // Error handling } }); request.setRetryPolicy(new DefaultRetryPolicy( 5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); RequestQueue queue = Volley.newRequestQueue(context); queue.add(request); ``` 需要注意的是,以上代码仅为示例,具体实现需要根据实际情况进行修改。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值