如何在Android中使用okhttp库向api(http post)添加参数

问题描述 投票:0回答:9

在我的 Android 应用程序中,我使用 okHttp 库。如何使用 okhttp 库向服务器(api)发送参数?目前我正在使用以下代码访问服务器现在需要使用 okhttp 库。

这是我的代码:

httpPost = new HttpPost("http://xxx.xxx.xxx.xx/user/login.json");
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("email".trim(), emailID));
nameValuePairs.add(new BasicNameValuePair("password".trim(), passWord));
httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
String response = new DefaultHttpClient().execute(httpPost, new BasicResponseHandler());
android okhttp
9个回答
53
投票

对于 OkHttp 3.x,FormEncodingBuilder 已被删除,请改用 FormBody.Builder

        RequestBody formBody = new FormBody.Builder()
                .add("email", "[email protected]")
                .add("tel", "90301171XX")
                .build();

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();

        Response response = client.newCall(request).execute();
        return response.body().string();

46
投票
    private final OkHttpClient client = new OkHttpClient();

      public void run() throws Exception {
        RequestBody formBody = new FormEncodingBuilder()
            .add("email", "[email protected]")
            .add("tel", "90301171XX")
            .build();
        Request request = new Request.Builder()
            .url("https://en.wikipedia.org/w/index.php")
            .post(formBody)
            .build();

        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

        System.out.println(response.body().string());
      }

7
投票

您只需在创建

RequestBody
对象之前格式化 POST 正文即可。

您可以手动执行此操作,但我建议您使用 Square(OkHttp 的制造商)的 MimeCraft 库。

在这种情况下,你需要

FormEncoding.Builder
类;将
contentType
设置为
"application/x-www-form-urlencoded"
并对每个键值对使用
add(name, value)


5
投票

没有一个答案对我有用,所以我玩了一下,下面的一个效果很好。分享以防万一有人遇到同样的问题:

进口:

import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

代码:

OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new MultipartBuilder()
        .type(MultipartBuilder.FORM) //this is what I say in my POSTman (Chrome plugin)
        .addFormDataPart("name", "test")
        .addFormDataPart("quality", "240p")
        .build();
Request request = new Request.Builder()
        .url(myUrl)
        .post(requestBody)
        .build();
try {
    Response response = client.newCall(request).execute();
    String responseString = response.body().string();
    response.body().close();
    // do whatever you need to do with responseString
}
catch (Exception e) {
    e.printStackTrace();
}

3
投票

通常为了避免 UI 线程中运行的代码带来的异常,根据预期的流程长度,在工作线程(线程或异步任务)中运行请求和响应流程。

    private void runInBackround(){

       new Thread(new Runnable() {
            @Override
            public void run() { 
                //method containing process logic.
                makeNetworkRequest(reqUrl);
            }
        }).start();
    }

    private void makeNetworkRequest(String reqUrl) {
       Log.d(TAG, "Booking started: ");
       OkHttpClient httpClient = new OkHttpClient();
       String responseString = "";

       Calendar c = Calendar.getInstance();
       SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
       String booked_at = sdf.format(c.getTime());

         try{
             RequestBody body = new FormBody.Builder()
                .add("place_id", id)
                .add("booked_at", booked_at)
                .add("booked_by", user_name.getText().toString())
                .add("booked_from", lat+"::"+lng)
                .add("phone_number", user_phone.getText().toString())
                .build();

        Request request = new Request.Builder()
                .url(reqUrl)
                .post(body)
                .build();

        Response response = httpClient
                .newCall(request)
                .execute();
        responseString =  response.body().string();
        response.body().close();
        Log.d(TAG, "Booking done: " + responseString);

        // Response node is JSON Object
        JSONObject booked = new JSONObject(responseString);
        final String okNo = booked.getJSONArray("added").getJSONObject(0).getString("response");
        Log.d(TAG, "Booking made response: " + okNo);

        runOnUiThread(new Runnable()
        {
            public void run()
            {
                if("OK" == okNo){
                    //display in short period of time
                    Toast.makeText(getApplicationContext(), "Booking Successful", Toast.LENGTH_LONG).show();
                }else{
                    //display in short period of time
                    Toast.makeText(getApplicationContext(), "Booking Not Successful", Toast.LENGTH_LONG).show();
                }
            }
        });

    } catch (MalformedURLException e) {
        Log.e(TAG, "MalformedURLException: " + e.getMessage());
    } catch (ProtocolException e) {
        Log.e(TAG, "ProtocolException: " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "IOException: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }

}

我希望它对将来的人有帮助。


2
投票

另一种方法(不使用 MimeCraft)是:

    parameters = "param1=text&param2=" + param2  // for example !
    request = new Request.Builder()
            .url(url + path)
            .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, parameters))
            .build();

并声明:

    public static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");

0
投票

(Kotlin版本) 你需要:

...
val formBody = FormBody.Builder()
    .add("your_key", "your_value")
    .build()
val newRequest: Request.Builder = Request.Builder()
    .url("api_url")
    .addHeader("Content-Type", "application/x-www-form-urlencoded")
    .post(formBody)
...

然后,如果您有安装了 npm body-parser 的 Nodejs Express 服务器,请务必执行以下操作:

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
...

0
投票

Kotlin 版本:

fun requestData(url: String): String {

    var formBody: RequestBody = FormBody.Builder()
        .add("email", "[email protected]")
        .add("tel", "90301171XX")
        .build();

    var client: OkHttpClient = OkHttpClient();
    var request: Request = Request.Builder()
        .url(url)
        .post(formBody)
        .build();

    var response: Response = client.newCall(request).execute();
    return response.body?.toString()!!
}

-1
投票

如果您想使用 OKHTTP 3 通过 API 发送 Post 数据,请尝试下面的简单代码

MediaType MEDIA_TYPE = MediaType.parse("application/json");
        String url = "https://cakeapi.trinitytuts.com/api/add";

        OkHttpClient client = new OkHttpClient();

        JSONObject postdata = new JSONObject();
        try {
            postdata.put("username", "name");
            postdata.put("password", "12345");
        } catch(JSONException e){
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        RequestBody body = RequestBody.create(MEDIA_TYPE, postdata.toString());

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .header("Accept", "application/json")
                .header("Content-Type", "application/json")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String mMessage = e.getMessage().toString();
                Log.w("failure Response", mMessage);
                //call.cancel();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String mMessage = response.body().string();
                Log.e(TAG, mMessage);
            }
        });

您可以在此处阅读使用 OKHTTP 3 GET 和 POST 请求将数据发送到服务器的完整教程:- https://trinitytuts.com/get-and-post-request-using-okhttp-in-android-application/

© www.soinside.com 2019 - 2024. All rights reserved.