Change the HttpParams code to httpurlconnection

3

I have a code that connects json to a mysql database, but HttpParams is obsolete in the java version I'm using, so I'd like to know how to do it or how best to put new parameters and keep that format to get the data, this is a login and password that I am doing. In the search I did, would httpURLConnection be a good alternative?

Java for Android

My code:

 private class AsyncDataClass extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {

        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
        HttpConnectionParams.setSoTimeout(httpParameters, 5000);

        HttpClient httpClient = new DefaultHttpClient(httpParameters);
        HttpPost httpPost = new HttpPost(params[0]);

        String jsonResult = "";
        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("username", params[1]));
            nameValuePairs.add(new BasicNameValuePair("password", params[2]));
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse response = httpClient.execute(httpPost);
            jsonResult = inputStreamToString(response.getEntity().getContent()).toString();

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonResult;
    }
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        System.out.println("Resulted Value: " + result);
        if(result.equals("") || result == null){
            Toast.makeText(MainActivity.this, "Server connection failed", Toast.LENGTH_LONG).show();
            return;
        }
        int jsonResult = returnParsedJsonObject(result);
        if(jsonResult == 0){
            Toast.makeText(MainActivity.this, "Invalid username or password", Toast.LENGTH_LONG).show();
            return;
        }
        if(jsonResult == 1){
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            intent.putExtra("USERNAME", enteredUsername);
            intent.putExtra("MESSAGE", "You have been successfully login");
            startActivity(intent);
        }
    }
    private StringBuilder inputStreamToString(InputStream is) {
        String rLine = "";
        StringBuilder answer = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        try {
            while ((rLine = br.readLine()) != null) {
                answer.append(rLine);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return answer;
    }
}
private int returnParsedJsonObject(String result){

    JSONObject resultObject = null;
    int returnedResult = 0;
    try {
        resultObject = new JSONObject(result);
        returnedResult = resultObject.getInt("success");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return returnedResult;
}
    
asked by anonymous 20.04.2016 / 16:19

1 answer

3

Dude the httpURLConnection for me works fine. Look at my class that has the get and the post:

public class HttpConnections {
 //método get
public static String get(String urlString){
    HttpURLConnection urlConnection = null;
    BufferedReader reader = null;
    String resposta = null;
    try {
        URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.connect();

        InputStream in = new BufferedInputStream(urlConnection.getInputStream());

        reader = new BufferedReader(new InputStreamReader(in));
        String line = "";
        StringBuffer buffer = new StringBuffer();
        while ((line = reader.readLine()) != null){
            buffer.append(line);
        }
        resposta = buffer.toString();
    }catch (Exception e){
        e.printStackTrace();
    }finally {
        if (urlConnection != null){
            urlConnection.disconnect();
        }
        try {
            reader.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    return resposta;
}
//post
public static String  performPostCall(String requestURL,HashMap<String, String> postDataParams) {
    URL url;
    String response = "";
    try {
        url = new URL(requestURL);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(15000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);


        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(os, "UTF-8"));
        writer.write(getPostDataString(postDataParams));

        writer.flush();
        writer.close();
        os.close();
        int responseCode=conn.getResponseCode();

        if (responseCode == HttpsURLConnection.HTTP_OK) {
            String line;
            BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((line=br.readLine()) != null) {
                response+=line;
            }
        }
        else {
            response="";

        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return response;
}
private static String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException{
    StringBuilder result = new StringBuilder();
    boolean first = true;
    for(Map.Entry<String, String> entry : params.entrySet()){
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
    }

    return result.toString();
} 
}

Then just call:

HttpConnections.get("sua url");//get

The post:

HashMap<String,String> login = new HashMap<>();
login.put("username","nome");
login.put("password","senha");
HttpConnections.performPostCall("sua url",login);

The two methods return a String with the answer. Example in your code:

private class AsyncDataClass extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
    //aqui fica quase da mesma forma

    HashMap<String,String> login = new HashMap<>();
    login.put("username",params[1]);
    login.put("password",params[2]);//passe quantos campos você quizer

    String resposta = HttpConnections.performPostCall(params[0],login);//já retorna uma String, então seu código de converter para String é desnecessário       
    return resposta;
}
@Override
protected void onPreExecute() {
    super.onPreExecute();
}
@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    System.out.println("Resulted Value: " + result);
    if(result.equals("") || result == null){
        Toast.makeText(MainActivity.this, "Server connection failed", Toast.LENGTH_LONG).show();
        return;
    }
    int jsonResult = returnParsedJsonObject(result);
    if(jsonResult == 0){
        Toast.makeText(MainActivity.this, "Invalid username or password", Toast.LENGTH_LONG).show();
        return;
    }
    if(jsonResult == 1){
        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
        intent.putExtra("USERNAME", enteredUsername);
        intent.putExtra("MESSAGE", "You have been successfully login");
        startActivity(intent);
    }
}    
private int returnParsedJsonObject(String result){
    JSONObject resultObject = null;
    int returnedResult = 0;
    try {
        resultObject = new JSONObject(result);
        returnedResult = resultObject.getInt("success");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return returnedResult;
}
}   
    
22.04.2016 / 19:11