2

UPDATE I'm using okHttp library, version 3.0.0 RC-1. I have a url and I have to send a post request with parameters. For example: https://myurl.com/login?username=123456&password=12345

I have code like this:

 public String okHttpRequest(){

    try {
        final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        }
        };

        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null,trustAllCerts, new java.security.SecureRandom());
        final javax.net.ssl.SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.sslSocketFactory(sslSocketFactory);
        builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        }).build();
        final OkHttpClient client = new OkHttpClient();

        HttpUrl url = HttpUrl.parse("https://myUrl.com/login").newBuilder()
                .addQueryParameter("username", "123456")
                .addQueryParameter("password", "123456")
                .build();
        Request request = new Request.Builder()
                .url(url)
                .build();


        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                Log.d("Request:", "Is NOT sent " + request.toString() + " METHOD: " + request.method());
                e.printStackTrace();
            }

            @Override
            public void onResponse(Response response) throws IOException {
                Log.d("Request:", "Is sent " + response.toString());
            }
        });
    }catch(Exception e){
        e.printStackTrace();
    }
    return "okHttp is Working!!! ";

}    

Whenever I try, It fails, so onFailure method is executing. What is the problem? Am I adding request params incorrectly? Please help...

BNK
  • 23,994
  • 8
  • 77
  • 87
Alvin
  • 894
  • 8
  • 16
  • try checking the request with Postman https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en And see whether your request is valid or not – reidzeibel Jan 11 '16 at 10:26
  • please learn http basics ... what is body and what is query string ... – Selvin Jan 11 '16 at 10:27
  • @Selvin I know, but I don't know the way to send request params with okhttp's post.. – Alvin Jan 11 '16 at 10:28
  • *to send request params with okhttp's post* ... and? you did it ... but server prolly "didn't understand" the request ... it may a) does not accept post b) does not accept x-www-form-urlencoded – Selvin Jan 11 '16 at 10:31
  • @Selvin How can I solve this then? – Alvin Jan 11 '16 at 10:33
  • learn http basics and make the server and client understand each other ... for start: read an exception in onFailure with understanding ... – Selvin Jan 11 '16 at 10:34
  • When I was using httpClient, httpPost everything was ok, requests were sent and was getting json response etc. All were ok, but as they are deprecated, I now want to use okhttp.. @Selvin – Alvin Jan 11 '16 at 10:35
  • Try to log the IoException you are getting in `onFailure`, the message and / or stack trace may help you. – Jonas Czech Jan 11 '16 at 10:58
  • @JonasCz here is the exception: javax.net.ssl.SSLPeerUnverifiedException: Hostname myUrl.com not verified: – Alvin Jan 11 '16 at 11:01
  • Are you using a self-signed HTTPS certificate ? If so, check this: https://stackoverflow.com/questions/25509296/trusting-all-certificates-with-okhttp – Jonas Czech Jan 11 '16 at 11:04
  • Make sure you are also using HostnameVerifier as before, and that it always returns true. – Jonas Czech Jan 11 '16 at 11:06
  • @JonasCz I can not apply them to my code... – Alvin Jan 11 '16 at 12:19
  • It should work. What do you mean by "can't apply to my code" ? – Jonas Czech Jan 11 '16 at 13:32
  • @JonasCz please check my updated code. The result is SSLPeerUnverifiedException again and again.. =( – Alvin Jan 11 '16 at 13:49
  • @Alvin: `SSLPeerUnverifiedException` because you don't use correctly as I answered at your previous question http://stackoverflow.com/questions/34671926/sslpeerunverifiedexception-okhttp. Here, you setHostnameVerifier for `builder` but you don't use that builder for `client`. So, please read my answer again to avoid that Exception – BNK Jan 11 '16 at 14:03
  • @BNK what dou you mean by **you don't use that builder for client** ? – Alvin Jan 11 '16 at 14:11
  • You are not actually using the client given to you by the builder, as also mentioned in the previous comment. Fix that and it should work – Jonas Czech Jan 11 '16 at 14:12
  • @Alvin: as I said, please read my answer at your previous question about `SSLPeerUnverifiedException `, then compare with your current code. – BNK Jan 11 '16 at 14:15
  • I really can't understand what you mean. Could you please write as code ? And additionally, it's sending GET request, not POST.. – Alvin Jan 11 '16 at 14:17
  • @BNK how to edit my code? – Alvin Jan 11 '16 at 14:27
  • Finally solved it! Thank you very very much!! @JonasCz – Alvin Jan 11 '16 at 14:58

1 Answers1

3

Yes, you are adding the query parameters incorrectly. Here's how it should be done:

final OkHttpClient client = new OkHttpClient();

HttpUrl url = HttpUrl.parse("https://myUrl.com/login").newBuilder()
        .addQueryParameter("password", "123456")
        .addQueryParameter("username", "123456")
        .build();

Request request = new Request.Builder()
       .url(url)
       .build();
(...)

The problem is that you are submitting your data in the body of the request, as if it were a HTML form submit, and not as a query parameter, as you intended. Using HttpUrl allows you to add query parameters to your URL.

Worth noting that you can also simply do this:

Request request = new Request.Builder()
       .url("https://myurl.com/login?username=123456&password=12345")
       .build();

So:

  • Use HttpUrl and it's builder to create your URL and add parameters.

  • Use FormBody to create the content of your request (as if it were a html form you're submitting), if you need it.

Also, make sure you have internet permission in your app, make sure you have an active internet connection, etc, but it seems you already have.

Note: this is for OkHttp 2.x (since that's what I use), but it should be the same or similar for 3.x.

Let me know if it works for you.

Jonas Czech
  • 12,018
  • 6
  • 44
  • 65
  • Result: Is NOT sent Request{method=GET, url=https://myUrl.com/login?&username=12345&password=12345, tag=null} METHOD: GET It has to be POST request.. – Alvin Jan 11 '16 at 10:57
  • @Alvin, try to log the IoException and add the stack trace to your question. I'll update my answer to make it use a Post request instead. – Jonas Czech Jan 11 '16 at 11:02
  • here is the exception: javax.net.ssl.SSLPeerUnverifiedException: Hostname myUrl.com not verified: – Alvin Jan 11 '16 at 11:02