Android Volley框架(一):StringRequest、JsonObjectRequest、JsonArrayRequest

本文介绍了Android中使用Volley框架进行GET/POST请求的基本步骤,特别是针对JsonObjectRequest的POST请求,当服务端需要字符串而非JSON时的处理方法。详细展示了从搭建环境到实现各步骤的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 Volley GET/POST请求的基本步骤:
 1. 创建一个RequestQueue对象。
 2. 创建一个 StringRequest/JsonObjectRequest/JsonArrayRequest 对象。
 3. 将 StringRequest/JsonObjectRequest/JsonArrayRequest 对象添加到RequestQueue里面。


关于JsonObjectRequest的post请求,有时无法正确解析上传的参数,原因在于服务端不接收json请求方式,只接收字符串,即服务端接收字符串,返回json串,这时需改写JsonObjectRequest方法,详见volley_JsonObjectRequestPost2()。


直接上代码,使用说明见注释:

第一步 搭建环境

下载jar包,新建工程,导入volley.jar


第二步 AndroidManifest.xml 文件

打开网络权限  (<uses-permission android:name="android.permission.INTERNET" />)

引入MyApplication  (android:name="com.example.volleyfrademo.MyApplication")

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.volleyfrademo"
    android:versionCode="1"
    android:versionName="1.0" >


    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="21" />
    
    <uses-permission android:name="android.permission.INTERNET"/>


    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" 
        android:name="com.example.volleyfrademo.MyApplication">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />


                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>


</manifest>


第三步 MyApplication.java 文件

package com.example.volleyfrademo;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.Volley;

import android.app.Application;
import android.text.TextUtils;

public class MyApplication extends Application {

	public static final String TAG = "MyApplication";
	private RequestQueue queues;
	private static MyApplication instance;
	
	@Override
	public void onCreate() {
		super.onCreate();
		instance = this;
	}
	
	public 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值