本文介绍了如何使用okhttp库在Android的参数添加到API(HTTP POST)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Andr​​oid应用程序,我使用 okHttp 库。我如何发送使用okhttp库参数服务器(API)?目前我使用下面的code访问服务器,现在需要使用okhttp库。

这是我的code:

  httpPost =新HttpPost(HTTP://xxx.xxx.xxx.xx/user/login.json);
namevaluepairs中=新的ArrayList<的NameValuePair>(2);
nameValuePairs.add(新BasicNameValuePair(电子邮件.trim(),EMAILID));
nameValuePairs.add(新BasicNameValuePair(密码.trim(),密码));
httpPost =新HttpPost(URL);
httpPost.setEntity(新UrlEn codedFormEntity(namevaluepairs中));
字符串响应=新DefaultHttpClient()执行(httpPost,新BasicResponseHandler())。
 

解决方案

 私人最终OkHttpClient客户端=新OkHttpClient();

      公共无效的run()抛出异常{
        RequestBody formBody =新FormEncodingBuilder()
            。新增(电子邮件,[email protected])
            。新增(电话,90301171XX)
            。建立();
        请求请求=新Request.Builder()
            .URL(https://en.wikipedia.org/w/index.php)
            。员额(formBody)
            。建立();

        响应响应= client.newCall(要求).execute();
        如果抛出IOException异常新(意外code+响应)(response.isSuccessful()!);

        的System.out.println(response.body()字符串());
      }
 

In my Android application, I am using okHttp library. How can I send parameters to the server(api) using the okhttp library? currently I am using the following code to access the server now need to use the okhttp library.

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());
解决方案
    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());
      }

这篇关于如何使用okhttp库在Android的参数添加到API(HTTP POST)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 17:28