相逢意气为君饮,系马高楼垂柳边。这篇文章主要讲述Android GSON使用POST方法相关的知识,希望能为你提供帮助。
我有以下PostActivity.java文件,它使用Method.GET成功从php服务器获取数据,但我需要更改GSON的方法,使用Method.POST而不是Method.GET,这样我就可以发送两个参数(操作和用户(pid))到服务器如下:
{
"operation":"listApps",
"user":{
"pid":"1"
}
}
【Android GSON使用POST方法】post activity.Java
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
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 com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PostActivity extends Activity {private static final String ENDPOINT = "http://www.locahost.com/api";
private RequestQueue requestQueue;
private Gson gson;
private List<
String>
posts_strs ;
private List<
Post>
posts ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
requestQueue = Volley.newRequestQueue(getApplicationContext());
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
gson = gsonBuilder.create();
posts_strs = new ArrayList<
String>
();
fetchPosts();
}private void fetchPosts() {
StringRequest request = new StringRequest(Request.Method.GET, ENDPOINT, onPostsLoaded, onPostsError);
requestQueue.add(request);
}private final Response.Listener<
String>
onPostsLoaded = new Response.Listener<
String>
() {
@Override
public void onResponse(String response) {posts = Arrays.asList(gson.fromJson(response, Post[].class));
ListView listview = (ListView) findViewById(R.id.postListView);
for (Post post : posts) {
posts_strs.add( post.ID + ": " + post.title);
}
ArrayAdapter<
String>
adapter = new ArrayAdapter<
String>
(PostActivity.this,R.layout.single_post_item,R.id.textView, posts_strs);
listview.setAdapter(adapter);
}
};
private final Response.ErrorListener onPostsError = new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(PostActivity.class.getSimpleName(), error.toString());
}
};
}
答案你必须更新
StringRequest
方法的fetchPosts
实例:StringRequest request = new StringRequest(Request.Method.POST, ENDPOINT, onPostsLoaded, onPostsError) {@Override
protected Map<
String, String>
getParams() {
Map<
String, String>
params = new HashMap<
String, String>
();
params.put("operation", "listApps");
// Create a POJO matching user structure and serialize this object to JSON to send it
params.put("user", "String matching format you want to send");
return params;
}
};
另一答案您可以使用以下代码,发送实体(java类),并返回实体(类)并将数据作为json发布到API
public class JsonRequest<
T>
extends Request<
T>
{
private static final String TAG = "JsonRequestHelper";
private final Gson gson = new Gson();
private final Class<
T>
returnType;
private final Object model;
private final Map<
String, String>
headers;
private final Response.Listener<
T>
listener;
/**
* Make a GET request and return a parsed object from JSON.
*
* @param urlURL of the request to make
* @param returnType Relevant class object, for Gson's reflection
* @param headersMap of request headers
*/
public JsonRequest(Integer httpVerb, String url, Class<
T>
returnType, Object model, Map<
String, String>
headers,
Response.Listener<
T>
listener, Response.ErrorListener errorListener) {
super(httpVerb, url, errorListener);
this.returnType = returnType;
this.model = model;
this.headers = headers;
this.listener = listener;
}@Override
public Map<
String, String>
getHeaders() throws AuthFailureError {
return headers != null ? headers : super.getHeaders();
}public static Map<
String, String>
getMapFromEntity(Object entity) {
try {
Map<
String, String>
map = new HashMap<
String, String>
();
Field[] fields = entity.getClass().getFields();
for (Field f : fields)
if (f != null &
&
f.getModifiers() == Modifier.PUBLIC)
map.put(f.getName(), f.get(entity).toString());
return map;
} catch (IllegalAccessException error) {
Log.e(TAG, error.getMessage());
return null;
}
}@Override
protected void deliverResponse(T response) {
listener.onResponse(response);
}@Override
public String getBodyContentType() {
return "application/json;
charset=utf-8";
}@Override
public byte[] getBody() {
return gson.toJson(this.model).getBytes();
}@Override
protected Response<
T>
parseNetworkResponse(NetworkResponse response) {
try {
String json = new String(
response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(
gson.fromJson(json, returnType),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
}
}
}
推荐阅读
- 线程“JavaFX Application Thread”中的异常java.lang.NoClassDefFoundError
- 必须使用app access_token调用此方法
- Facebook通知API(“必须使用app access_token调用此方法”)
- 通过Facebook APP获得与计数一样的帖子
- win8默认网关不可用的处理办法
- win8.1禁用驱动程序强制签名的办法【图文】
- win8.1自动登录微软账户的办法【图文】
- win8.1纯净版通知栏图标显示灰色无法选中处理办法【图文】
- Win8系统IE10浏览器登录工行网银提示无法显示此页处理办法