How to send parameters to a server?

2

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

Now I need to communicate with a server via the post method in an Android application. I have managed to do this, however I can not send parameters to the server.

The server must register and send a response and it should receive an image and some other data and I already researched and can not do that.

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 HttpClient and neither NameValuePair nor HttpUrlConnection does not have the setEntity method. That's the problem. The internet only talks about this HttpClient and it does not work for me. I'm a beginner and I can not continue and I have time to finish. just send the parameters to the server! just this!

    
asked by anonymous 07.10.2015 / 22:45

3 answers

3

The problem with Android Studio not recognizing HttpClient is that it got 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 okHttp .

In the okHttp repository itself, you have 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 give an example of how to make a GET in a URL and store it 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 should 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 sync now at the top of the screen.

    
10.10.2015 / 04:10
1
The emanuelsn friend's answer is really great, just to complete it if you have a class and want it to be converted to JSon directly without that bureaucracy of having to mount it in your hand you can also use the GSON lib, she works with annotations, makes the job much simpler.

to use it in Gradle:

compile 'com.google.code.gson:gson:2.2.4'
    
13.10.2015 / 13:42
-1

I do using parameters in the URL, cryptograph the parameters and send and parse these server side. For posting on the POST envelope a look at this response from StackOverflow in English:

link

Something like this:

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
}
    
08.10.2015 / 14:43