发送Post请求一般有两种格式:Json格式和表单格式来发送请求。
这里两个工具类来使用发送post请求:
表单格式:
//表单body
FormBody body = new FormBody.Builder().add("news_id", news_id + "").add("fromname", fromname).add("time", time).build();
public static void getPost(FormBody body, String httpurl) {
OkHttpClient client = new OkHttpClient();
Request.Builder builder = new Builder();
builder.post(body);
builder.url(httpurl);
Request request = builder.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onResponse(Call arg0, Response arg1) throws IOException {
// TODO Auto-generated method stub
Log.i("lpl", arg1.body().string());
}
@Override
public void onFailure(Call arg0, IOException arg1) {
// TODO Auto-generated method stub
}
});
}
Json格式发送:
public static String MypostJson(String api, Object RequestJsonbean) throws IOException {
/**
* 返回的仍然是json格式
*/
Gson gson = new Gson();
String json = gson.toJson(RequestJsonbean);
OkHttpClient client = new OkHttpClient();
//json body
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder().url(api).post(body).build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}
RequestJsonbean是你的javabean对象