简体   繁体   English

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

[英]How to add parameters to api (http post) using okhttp library in Android

In my Android application, I am using okHttp library.在我的 Android 应用程序中,我使用的是okHttp库。 How can I send parameters to the server(api) using the okhttp library?如何使用 okhttp 库向服务器(api)发送参数? currently I am using the following code to access the server now need to use the okhttp library.目前我正在使用以下代码访问服务器,现在需要使用 okhttp 库。

this is the my code:这是我的代码:

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());

For OkHttp 3.x, FormEncodingBuilder was removed, use FormBody.Builder instead对于 OkHttp 3.x,FormEncodingBuilder 被移除,使用 FormBody.Builder 代替

        RequestBody formBody = new FormBody.Builder()
                .add("email", "Jurassic@Park.com")
                .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();
    private final OkHttpClient client = new OkHttpClient();

      public void run() throws Exception {
        RequestBody formBody = new FormEncodingBuilder()
            .add("email", "Jurassic@Park.com")
            .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());
      }

You just need to format the body of the POST before creating the RequestBody object.您只需要在创建RequestBody对象之前格式化 POST 的RequestBody

You could do this manually, but I'd suggest you use the MimeCraft library from Square (makers of OkHttp).您可以手动执行此操作,但我建议您使用 Square(OkHttp 的制造商)的MimeCraft库。

In this case you'd need the FormEncoding.Builder class;在这种情况下,您需要FormEncoding.Builder类; set the contentType to "application/x-www-form-urlencoded" and use add(name, value) for each key-value pair.contentType设置为"application/x-www-form-urlencoded"并为每个键值对使用add(name, value)

None of the answers worked for me, so I played around and below one worked fine.没有一个答案对我有用,所以我四处玩,下面一个工作得很好。 Sharing just in case someone gets stuck with the same issue:分享以防万一有人遇到同样的问题:

Imports:进口:

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;

Code:代码:

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();
}

Usually to avoid Exceptions brought about by the code running in UI thread, run the request and response process in a worker thread (Thread or Asynch task) depending on the anticipated length of the process.通常为了避免运行在 UI 线程中的代码带来的 Exceptions,根据预期的进程长度,在工作线程(线程或异步任务)中运行请求和响应进程。

    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());
    }

}

I hope it helps someone there.我希望它可以帮助那里的人。

Another way (without MimeCraft), is to do :另一种方法(没有 MimeCraft)是:

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

and declare :并声明:

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

(Kotlin version) You would need: (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)
...

Then, if you have a nodejs express server with npm body-parser installed, be sure to do following:然后,如果您有安装了 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 }));
...

Kotlin Version:科特林版本:

fun requestData(url: String): String {

    var formBody: RequestBody = FormBody.Builder()
        .add("email", "Jurassic@Park.com")
        .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()!!
}

If you want to send Post data through API using OKHTTP 3 please try below simple code如果您想使用 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);
            }
        });

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM