Change Httpparams code to httpurlconnection

Asked

Viewed 342 times

3

I have a code that connects json to a mysql database, but Httpparams is obsolete in the version of java I’m using, so I’d like to know how to do it or how best to put new parameters and maintain this format to take the data, This is from a login and password I’m doing. In the research I did, httpURLConnection would 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;
}

1 answer

3


Guy the httpURLConnection for me works great. Check out 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 you 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;
}
}   
  • Thank you so much for the answer, I just want to know, in this code of yours, you don’t need to use Asynctask? Also, what is the best way I can pass the login and password parameters to json? I am now entering java android and this is a bit confusing for me, should be simple thing. Thanks

  • Yes, you need to use Asynctask. To pass the data is very similar, just Hashmap<String,String> login = new Hashmap<>(); login.put("username","name"); login.put("password","password"); login.put("other","other"); . I edited the code, I think it’s better now.

  • Very good guy, it was exactly what I needed, vlw even!

  • @Fabianoaraujo Good tip +1

Browser other questions tagged

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