Android如何在不使用废弃方法的情况下向服务器发送HTTPS POST请求?

5

我的应用程序使用的是通过这个来源的答案发送https请求。现在其中一些apache方法已经过时。有人能帮我以新的方式解决吗?


你可以使用 HttpUrlConnection 替代已弃用的 Apache 方法。 - Satyen Udeshi
我需要使用SSL,并且请更清晰一些。 - nAkhmedov
由于您需要详细信息,这里有一个类似的 https://dev59.com/RGQn5IYBdhLWcg3w36XV#16507195,请在评论中说明您需要进一步的帮助。 - Satyen Udeshi
6个回答

5
为了避免在API连接中使用过时的方法,请考虑使用Retrofit。它是一个第三方库,可以使HTTP通信更加简单。
在使用Retrofit时,您可以创建一个API端点接口,然后像使用方法一样使用它。其余的HTTP请求由该库管理。
这是Retrofit Github主页的链接: http://square.github.io/retrofit/

3

HttpURLConnection是SDK的一部分,从API 1开始就可以使用,您可以使用相同的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/

这些链接提供了有关在Java和Android上发送HTTP请求的详细信息。

1
请检查下面的函数:
  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;
}

0

如果你想在API 22和23上继续使用HttpClient, 请在项目的Lib文件夹中添加org.apache.http.legacy.jar, 你会在Android\sdk\platforms\android-23\optional..中得到.jar文件。

如果你正在使用Android Studio,在将jar文件复制粘贴到lib文件夹后, 右键单击jar文件,然后点击add as library

你的问题将会得到解决。如需任何帮助,请留言。 谢谢!


0

在Android SDK 23中

HttpClient已被弃用,您可以将代码迁移到HttpURLConnection

类似这样

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

0

您可以使用此方法进行任何目的的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>')
}

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接