【问题标题】:How to add parameters to api (http post) using okhttp library in Android如何在Android中使用okhttp库向api(http post)添加参数
【发布时间】:2014-08-05 16:25:31
【问题描述】:

在我的 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


【解决方案1】:

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

【讨论】:

  • 如何向 formBody 添加键和参数?我动态地同时收到“电子邮件”和“Jurassic@Park.com”,而且我必须有一个 RequestBody。谢谢。
  • @Alvin 是的,当然。就这样吧,RequestBody formBody = new FormBody.Builder() .add(dynamicEmailKey, dynamicEmailParam) .build();
  • @宝乐,为什么mvnrepository.com没有3.x版本?
  • okhttp3 使用持久化版本控制并将版本放在组 id 和包名称mvnrepository.com/artifact/com.squareup.okhttp3/okhttp
  • 其他解决方案基于旧版本的 OkHttp。这是最新的。
【解决方案2】:
    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());
      }

【讨论】:

    【解决方案3】:

    您只需要在创建 RequestBody 对象之前格式化 POST 的正文。

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

    在这种情况下,您需要 FormEncoding.Builder 类;将contentType 设置为"application/x-www-form-urlencoded" 并为每个键值对使用add(name, value)

    【讨论】:

    • 当您在查看 MimeCraft 时,如果您的最终目标是一个 Restful api,您可能想要查看 Retrofit(也由 Square 提供)
    • 这也适用于get 请求吗?我的意思是当FormEncoding.Builderget请求一起使用时,参数是否添加到url中?
    • 回答我自己的问题,当FormEncoding.BuilderGET 请求一起使用时,OkHttp 会抛出类似GET requests doesn't support request body 的异常。
    【解决方案4】:

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

    进口:

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

    【讨论】:

      【解决方案5】:

      通常为了避免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());
          }
      
      }
      

      我希望它可以帮助那里的人。

      【讨论】:

      • 这正是我所需要的!
      【解决方案6】:

      另一种方法(没有 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");
      

      【讨论】:

        【解决方案7】:

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

        【讨论】:

          【解决方案8】:

          Kotlin 版本:

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

          【讨论】:

            【解决方案9】:

            如果您想使用 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/

            【讨论】:

              猜你喜欢
              • 2011-03-18
              • 2016-03-01
              • 2015-06-30
              • 2015-07-20
              • 1970-01-01
              • 2018-12-26
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多