How to send parameters to a server?

Asked

Viewed 1,573 times

2

I started learning Android programming very little time ago. I was programming in Java desktop but I never made any application to communicate with a server.

Now I need to communicate with a server through the method post in an Android application. I was able to do this, but I can’t send parameters to the server.

The server must register and send a reply and it should receive an image and some other data and I already searched and I can’t do it.

Follow my code so far:

    //Converte um InputStream em String
    private String readIt(InputStream stream, int len) throws Exception {
        try {
            Reader reader = null;
            reader = new InputStreamReader(stream, "UTF-8");
            char[] buffer = new char[len];
            reader.read(buffer);
            return new String(buffer);
        }catch(Exception e)
        {
            throw e;
        }
    }

    //O código propriamente dito que se comunicará com o servidor
    private String downloadUrl(String myUrl) throws Exception {

        InputStream is = null;
        String respStr = null;

        int len = 500;

        try {
            URL url = new URL(myUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);

            conn.connect();

            is = conn.getInputStream();

            respStr = readIt(is, len);

        } catch(Exception e)
        {
            throw e;
        } finally {
            if (is != null) {
                is.close();
            }
        }

        return respStr;
    }
}

My Android Studio does not recognize the HttpClient and neither is this NameValuePair and the HttpUrlConnection does not have the method setEntity. That’s the problem. The internet only talks about this HttpClient and it’s not right for me. I’m a beginner and I can’t continue and I have time to finish . just send the parameters to the server! only this!

3 answers

3

Android Studio problem does not recognize the HttpClient, is that he stayed deprecated in API 22 and was removed in API 23.

The solution I found to work with requests on a server/webservice, was to use the okHttp.

In the repository itself of okHttp, has an example of how to use POST.

public static final MediaType JSON
    = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(JSON, json);
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  Response response = client.newCall(request).execute();
  return response.body().string();
}

I also leave below an example of how to make a GET in a URL and store in a String.

OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
  Request request = new Request.Builder()
      .url(url)
      .build();

  Response response = client.newCall(request).execute();
  return response.body().string();
}

How to include Okhttp in Gradle?

To include Okhttp in Gradle, you must open the build.gradle of the application and add the line within dependences.

compile 'com.squareup.okhttp:okhttp:2.5.0'

After that, just click on sync now at the top of the screen.

1

The reply of the friend emanuelsn is really great, just to complete if you have a class and want it to be converted to direct Json without that bureaucracy of having to ride it in the hand you can also use the lib GSON, very good, it works with Annotations, makes work much simpler.

to use it in Gradle:

compile 'com.google.code.gson:gson:2.2.4'

-1

I do it using parameters in the URL, cryptograph the parameters and upload and parse these on the server side. To send the POST envelope a look at this Stackoverflow response in English:

https://stackoverflow.com/questions/3288823/how-to-add-parameters-in-android-http-post

Something like that:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/myexample.php");

try {
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("id", "12345"));
    nameValuePairs.add(new BasicNameValuePair("stringdata", "stackoverflow.com is Cool!"));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute HTTP Post Request
    HttpResponse response = httpclient.execute(httppost);

} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
} catch (IOException e) {
    // TODO Auto-generated catch block
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.