Android 向服务器发送 https post 请求而不使用弃用的方法

Android send https post request to the server without deprecated methods

在我的应用程序中,使用了通过 https 发送请求,遵循 this source answer。现在其中一些 apache 方法已弃用。谁能帮我用新方法解决问题?

在 Android SDK 23

HttpClient 已弃用,您可以在 HttpURLConnection

中迁移您的代码

像这样

URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.connect();

请检查以下功能:

  public String makeServiceCall(String url1, MultipartEntity reqEntity) {
    try {
        // http client
        URL url= new URL(url1);
        HttpURLConnection httpClient = (HttpURLConnection) url.openConnection();
        httpClient.setRequestMethod("POST");
        httpClient.setUseCaches(false);
        httpClient.setDoInput(true);
        httpClient.setDoOutput(true);
        httpClient.setRequestProperty("Connection", "Keep-Alive");
        httpClient.addRequestProperty("Content-length", reqEntity.getContentLength()+"");


         OutputStream os = httpClient.getOutputStream();
         reqEntity.writeTo(httpClient.getOutputStream());
         os.close();
         httpClient.connect();

         if (httpClient.getResponseCode() == HttpURLConnection.HTTP_OK) {
             return readStream(httpClient.getInputStream());
         }


    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

HttpURLConnection 是来自 API 1 的 SDK 的一部分,您可以使用相同的 http://developer.android.com/reference/java/net/HttpURLConnection.html.

// HTTP POST request
private void sendPost() throws Exception {

    //Your server URL
    String url = "https://selfsolve.apple.com/wcResults.do";
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    //Request Parameters you want to send
    String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";

    // Send post request
    con.setDoOutput(true);// Should be part of code only for .Net web-services else no need for PHP
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    //print result
    System.out.println(response.toString());

}

您可以从

获得更多详细信息
  1. http://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/
  2. http://syntx.io/how-to-send-an-http-request-from-android-using-httpurlconnection/

如果您想在 API 级别 22 和 23 中继续使用 HttpClient.. 在你项目的 org.apache.http.legacy.jar 文件夹中添加 org.apache.http.legacy.jar, 将在 Android\sdk\platforms\android-23\optional..

中获取 .jar 文件

如果你使用 android Studio,在 lib 文件夹中复制粘贴 jar 文件后,右键单击 jar 文件并单击 添加为库

你的问题将得到解决..如果需要任何帮助,请发表评论。 谢谢!

要避免在 API 连接中使用已弃用的方法,请考虑使用 Retrofit。它是一个第三方库,使 HTTP 通信更加简单。

使用 Retrofit 时,您可以创建 API 端点的接口并像使用方法一样使用它。 HTTP 请求的其余部分由图书馆管理。

这是 Retrofit github 主页的 link: http://square.github.io/retrofit/

您可以将此方法用于 Get 或 Post 任何目的。只需将此方法用于服务器请求。

public void RequestToServer() {
        //  String User_id = "h";
        AsyncHttpClient client = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        // params.put("uid", User_id.toString());
        client.post("http:// Your Url", params, new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(String s) {
                super.onSuccess(s);
                Log.d("Server Response for success :", s);
                tv.append("service_ReloadSqlDB" + "    " + s);
            }

            @Override
            public void onFailure(Throwable throwable) {
                super.onFailure(throwable);
                Log.d("Server Response for onFailure ", throwable.toString());
            }
        });

    }

你还需要一个 jar 文件 = android-async-http-1.3.1.jar 下载这个 jar 并将你的 android 项目添加到 libs 文件夹中 之后将其添加到您的 build.gradle

dependencies {

compile files('libs/<android-async-http-1.3.1.jar>')
}

最终重建您的项目,运行 应用程序,获取您的服务器响应。