Thursday, 28 May 2015

Android play song continuously(ArrayList) in service





package com.source;

import java.io.IOException;
import java.util.ArrayList;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.drm.DrmStore.Playback;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service implements OnCompletionListener,
MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener{

Context context;
private static final String ACTION_PLAY = "PLAY";
private static final String TAG = "SONG SERVICE";
MediaPlayer mediaPlayer;
private int currentTrack = 0;
ArrayList<String> list;
public MyService() {
context=getBaseContext();
}

@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
list = (ArrayList<String>)intent.getSerializableExtra("arraylist");
int count=0;
Log.d(TAG, "total count:"+list.size());
//playing song one by one
for (String string : list) {
//play(string);
count++;
Log.d(TAG, "count:"+list);
}
play(currentTrack);
Log.d(TAG, "count:"+count);
if(count==list.size()){
//stopSelf();
Log.d(TAG, "stoping service");
//mediaPlayer.setOnCompletionListener(this);
}else{
Log.d(TAG, "not stoping service");
}

if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
Log.d(TAG, "oncommat");
}
return START_STICKY;
}

@Override
public void onCreate() {

Toast.makeText(this, "Service was Created", Toast.LENGTH_LONG).show();
}



@Override
public void onStart(Intent intent, int startId) {
// Perform your long running operations here.
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
}

@Override
public void onDestroy() {
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
Log.d("service", "destroyed");
if (mediaPlayer.isPlaying()) {
     mediaPlayer.stop();
   }
   mediaPlayer.release();
}



@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
return false;
}

@Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub

}

private void play(int id) {


if(mediaPlayer!=null && mediaPlayer.isPlaying()){
Log.d("*****begin*****", "playing");
stopPlaying();
Log.d("*****begin*****", "stoping");
     } else{
    Log.d("*****begin*****", "nothing");
     }

Log.d("*****play count*****", "="+currentTrack);
Log.i("******playing", list.get(currentTrack));

Uri myUri1 = Uri.parse(list.get(id));
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
mediaPlayer.setOnPreparedListener(this);
//mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnErrorListener(this);
try {
mediaPlayer.setDataSource(context, myUri1);
Log.i("******playing", myUri1.getPath());
} catch (IllegalArgumentException e) {
            Toast.makeText(context, "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
        } catch (SecurityException e) {
            Toast.makeText(context, "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
        } catch (IllegalStateException e) {
            Toast.makeText(context, "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            e.printStackTrace();
        }

try {
mediaPlayer.prepare();
        } catch (IllegalStateException e) {
            Toast.makeText(context, "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            Toast.makeText(context, "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
        }

mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

@Override
public void onCompletion(MediaPlayer mp) {
currentTrack=currentTrack+1;
play(currentTrack);
/* currentTrack = (currentTrack + 1) % list.size();
Uri nextTrack=Uri.parse(list.get(currentTrack));

try {
mediaPlayer.setDataSource(context,nextTrack);
mediaPlayer.prepare();
// mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}*/

}
});

        mediaPlayer.start();
}

private void stopPlaying() {
        if (mediaPlayer != null) {
        mediaPlayer.stop();
        mediaPlayer.release();
        mediaPlayer = null;
       }
    }

@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub

}

}

call the service




stopService();
startService(getSongsFromAlbum(v.getTag().toString()));



private void startService(ArrayList<String> list) {
Intent intent=new Intent(getActivity(),MyService.class);
intent.putExtra("arraylist", list);
getActivity().startService(intent);

}

private void stopService() {
getActivity().stopService(new Intent(getActivity(),MyService.class));
}



Friday, 22 May 2015

Swipable Tabs changing app icon as well as tab icon


SongGalleryActivity .java

package com.mtag;

import com.util.NotificationPanel;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

@SuppressLint("NewApi")
public class SongGalleryActivity extends FragmentActivity  implements
ActionBar.TabListener {
int backButtonCount=0;
private ViewPager viewPager;
    private TabsPagerAdapter mAdapter;
    private android.app.ActionBar actionBar;
    // Tab titles
    private String[] tabs = { "Genres", "Artists", "Albums","Songs","PlayLists" };
 
    private static final int[] ICONS = new int[] {
        R.drawable.genre_inactive,
        R.drawable.artist_inactive,
        R.drawable.albums_inactive,
        R.drawable.songs_inactive,
        R.drawable.lists_inactive,
};

    private static final int[] ICONS_SELECTED = new int[] {
        R.drawable.genre_active,
        R.drawable.artist_active,
        R.drawable.albums_active,
        R.drawable.songs_active,
        R.drawable.lists_active,
};
 
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_song_gallery);

String val=getIntent().getStringExtra("DO");
Log.d("value..............", "::::"+val);

// Initilization
        viewPager = (ViewPager) findViewById(R.id.pager);
        actionBar = getActionBar();
        mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

        viewPager.setAdapter(mAdapter);
        actionBar.setHomeButtonEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);    
        LayoutInflater mInflater = LayoutInflater.from(this);
        View mCustomView = mInflater.inflate(R.layout.custom_actionbar, null);
        actionBar.setCustomView(mCustomView);
        actionBar.setDisplayShowCustomEnabled(true);

/*     // Adding Tabs
        for (String tab_name : tabs) {
            actionBar.addTab(actionBar.newTab().setText(tab_name)
                    .setTabListener(this));
        }*/
     
        // instead of NewsFeedActivity you have to use your activity name here
        for (int i=0; i < tabs.length; i++)
                {
                actionBar.addTab(actionBar.newTab().setText(tabs[i])
                                         .setIcon(SongGalleryActivity.this.getResources().getDrawable(ICONS[i]))
                                         .setTabListener(this));
                }//endfor
     
        actionBar.setStackedBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.white)));
     
       //actionBar.setStackedBackgroundDrawable(getResources().getDrawable(R.color.white));
     
        /**
         * on swiping the viewpager make respective tab selected
         * */
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                // on changing the page
                // make respected tab selected
                actionBar.setSelectedNavigationItem(position);
 //actionBar.setIcon(ICONS_SELECTED[position]);// this is for changing logo in the applcation also
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
     
}

@Override
public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub

}

@SuppressLint("NewApi")
@Override
public void onTabSelected(Tab tab, FragmentTransaction arg1) {
viewPager.setCurrentItem(tab.getPosition());
tab.setIcon(ICONS_SELECTED[tab.getPosition()]);
}

@Override
public void onTabUnselected(Tab tab, FragmentTransaction arg1) {
tab.setIcon(ICONS[tab.getPosition()]);

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}

@Override
public void onBackPressed() {

if(backButtonCount >= 1)
   {

NotificationPanel notificationPanel=new NotificationPanel(this);
notificationPanel.notificationCancel();

       Intent intent = new Intent(Intent.ACTION_MAIN);
       intent.addCategory(Intent.CATEGORY_HOME);
       intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
       startActivity(intent);
   }
   else
   {
       Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
       backButtonCount++;
   }
}
}


Note :

actionBar.setIcon(ICONS_SELECTED[position]);// this is for changing logo in the applcation also


if u add this 

   public void onPageSelected(int position) {
                // on changing the page
                // make respected tab selected
                actionBar.setSelectedNavigationItem(position);
               actionBar.setIcon(ICONS_SELECTED[position]);
            }

the application icon also will changed 




TabsPagerAdapter .java


package com.mtag;

import com.viewpagerindicator.IconPagerAdapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class TabsPagerAdapter extends FragmentPagerAdapter implements IconPagerAdapter {


public TabsPagerAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}

@Override
public Fragment getItem(int index) {
switch (index) {
        case 0:
            // Genres fragment activity
            return new GenresFragment();
        case 1:
            // Artist fragment activity
            return new ArtistsFragment();
        case 2:
            // ALbum fragment activity
            return new AlbumsFragment();
     
        case 4:
            // Playlist fragment activity
            return new PlaylistFragment();
        case 3:
            // ALbum fragment activity
            return new SongsFragment();
        }

        return null;
}

@Override
public int getCount() {
// TODO Auto-generated method stub
return 5;
}

@Override
public int getIconResIdNormal(int index) {
// TODO Auto-generated method stub
return 0;
}

@Override
public int getIconResIdSelected(int index) {
// TODO Auto-generated method stub
return 0;
}

@Override
public int getBackgroundResIdSelected(int index) {
// TODO Auto-generated method stub
return 0;
}

@Override
public int getBackgroundResIdNormal(int index) {
// TODO Auto-generated method stub
return 0;
}



}


fragment

package com.mtag;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Set;

import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SectionIndexer;
import android.widget.TextView;
import android.widget.Toast;

import com.source.Song;
import com.util.NotificationPanel;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class SongsFragment extends Fragment{

LayoutInflater inflater;
ListView listView;
View rootView;
private ArrayList<Song> songList;
ArtistsAdapter adapter;
MediaPlayer mediaPlayer;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.inflater=inflater;
View rootView = inflater.inflate(R.layout.fragment_songs, container, false);     
this.rootView=rootView;
this.inflater=inflater;
GUI();
       return rootView;
}

private void GUI() {
String val=getActivity().getIntent().getStringExtra("DO");
Log.d("value..............", "::::"+val);
listView=(ListView)rootView.findViewById(R.id.listViewSongs);
songList = new ArrayList<Song>();
//get songs from device
getSongList();
//sort alphabetically by title
Collections.sort(songList, new Comparator<Song>(){
public int compare(Song a, Song b){
return a.getTitle().compareTo(b.getTitle());
}
});
fillAdapter();
//create and set adapter
/*com.source.SongAdapter adapter=new com.source.SongAdapter(getActivity(), songList);
listView.setAdapter(adapter);*/
}
private void fillAdapter() {
if(null != songList || songList.size() > 0){
adapter=new ArtistsAdapter(getActivity());
listView.setAdapter(adapter);
}
}
class ArtistsAdapter extends ArrayAdapter implements SectionIndexer{
Context context;
HashMap<String, Integer> alphaIndexer;
       String[] sections;
public ArtistsAdapter(Context context) {
super(context, R.layout.row_song_song, songList);
this.context = context;
alphaIndexer = new HashMap<String, Integer>();
           int size = songList.size();
 
           for (int x = 0; x < size; x++) {
               Song s = songList.get(x);
 
// get the first letter of the store
               String ch =  s.getAlbum().substring(0, 1);
// convert to uppercase otherwise lowercase a -z will be sorted after upper A-Z
               ch = ch.toUpperCase();
 
// HashMap will prevent duplicates
               alphaIndexer.put(ch, x);
           }
 
           Set<String> sectionLetters = alphaIndexer.keySet();
 
   // create a list from the set to sort
           ArrayList<String> sectionList = new ArrayList<String>(sectionLetters); 
 
           Collections.sort(sectionList);
 
           sections = new String[sectionList.size()];
 
           sectionList.toArray(sections);
}
@Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final Holder holder;
if (convertView == null) {
holder = new Holder();
convertView = (LinearLayout) LayoutInflater.from(context)
.inflate(R.layout.row_song_song, null);
holder.texSongName=(TextView)convertView.findViewById(R.id.song_title);
holder.textSongDetail=(TextView)convertView.findViewById(R.id.song_data);
holder.layout=(LinearLayout)convertView.findViewById(R.id.song_layout);
convertView.setTag(holder);

} else {
holder = (Holder) convertView.getTag();
}
holder.layout.setTag(songList.get(position).getData());
holder.texSongName.setText(songList.get(position).getTitle());
holder.textSongDetail.setText(songList.get(position).getArtist());
//holder.texSongName.setTag(songList.get(position).getData());
holder.layout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
play(v.getTag().toString());
// Log.d("id", ":"+v.getId());
Toast.makeText(getContext(), "clicked"+v.getTag().toString(), Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
class Holder{
TextView texSongName,textSongDetail;
LinearLayout layout;
}

@Override
public Object[] getSections() {
// TODO Auto-generated method stub
return sections;
}

public int getPositionForSection(int section) {
          return alphaIndexer.get(sections[section]);
      }

@Override
public int getSectionForPosition(int position) {
// TODO Auto-generated method stub
return 1;
}
}
int count=0;
String playFile;
private void play(String path) {
count++;
playFile=path;
//showNotification();
new NotificationPanel(getActivity());
if(mediaPlayer!=null && mediaPlayer.isPlaying()){
Log.d("*****begin*****", "playing");
stopPlaying();
Log.d("*****begin*****", "stoping");
     } else{
    Log.d("*****begin*****", "nothing");
     }

Uri myUri1 = Uri.parse(path);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(getActivity(), myUri1);
} catch (IllegalArgumentException e) {
            Toast.makeText(getActivity(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
        } catch (SecurityException e) {
            Toast.makeText(getActivity(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
        } catch (IllegalStateException e) {
            Toast.makeText(getActivity(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            e.printStackTrace();
        }
try {
mediaPlayer.prepare();
        } catch (IllegalStateException e) {
            Toast.makeText(getActivity(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            Toast.makeText(getActivity(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
        }
        mediaPlayer.start();
   
}
private void stopPlaying() { 
        if (mediaPlayer != null) {
        mediaPlayer.stop();
        mediaPlayer.release();
        mediaPlayer = null;
       } 
    } 

//method to retrieve song info from deviceyyyy
public void getSongList(){
//query external audio
ContentResolver musicResolver = getActivity().getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
//iterate over results if valid
if(musicCursor!=null && musicCursor.moveToFirst()){
//get columns
int titleColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media._ID);
int artistColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.ARTIST);
int albumColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.ALBUM);
int trackColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.TRACK);
int dataColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.DATA);
//add songs to list
do {
long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
String thisAlbum = musicCursor.getString(albumColumn);
String thisTrack = musicCursor.getString(trackColumn);
String thisData = musicCursor.getString(dataColumn);
songList.add(new Song(thisId, thisTitle, thisArtist,thisAlbum,thisTrack,thisData));

while (musicCursor.moveToNext());
}
}
}





Wednesday, 6 May 2015

send data in post form-data and x-www-form-urlencoded

there some mothod in REST api sending data in the post method,

1.normal form data is one way to handle this sending post,
public class JSONParser {

static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            //post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
            Log.e("JSON", json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);          
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
   
   
    @SuppressLint("NewApi")
public static String excutePost(String targetURL, String urlParameters) throws MalformedURLException, IOException
    {
     /* URL url;
      HttpURLConnection connection = null;
      try {
        //Create connection
        url = new URL(targetURL);
        connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type",
             "application/x-www-form-urlencoded");
 
        connection.setRequestProperty("Content-Length", "" +
                 Integer.toString(urlParameters.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");
 
        connection.setUseCaches (false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        //Send request
        DataOutputStream wr = new DataOutputStream (
                    connection.getOutputStream ());
        wr.writeBytes (urlParameters);
        wr.flush ();
        wr.close ();

        //Get Response
        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while((line = rd.readLine()) != null) {
          response.append(line);
          response.append('\r');
        }
        rd.close();
        return response.toString();

      } catch (Exception e) {

        e.printStackTrace();
        return null;

      } finally {

        if(connection != null) {
          connection.disconnect();
        }
      }*/
   
    // String url = "http://example.com";
    String charset = "UTF-8";  // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name()
    String param1 = "9880938687";
    String param2 = "value2";
    // ...
   
    String query = null;
try {
query = String.format("mobile=%s&param2=%s",
    URLEncoder.encode(param1, charset),
    URLEncoder.encode(param2, charset));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
   
    URLConnection connection = new URL(targetURL).openConnection();
    connection.setDoOutput(true); // Triggers POST.
    connection.setRequestProperty("Accept-Charset", charset);
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
   
    try (OutputStream output = connection.getOutputStream()) {
       output.write(query.getBytes(charset));
    }
   
    //InputStream response = connection.getInputStream();
    // ..
        //Get Response
        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while((line = rd.readLine()) != null) {
          response.append(line);
          response.append('\r');
        }
        rd.close();
        System.out.println("***"+response.toString());
        return response.toString();
    }

}

Using java.net.URLConnection to fire and handle HTTP requests?

Preparing

We first need to know at least the URL and the charset. The parameters are optional and depend on the functional requirements.
String url = "http://example.com";
String charset = "UTF-8";  // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name()
String param1 = "value1";
String param2 = "value2";
// ... 
 
String query = String.format("param1=%s&param2=%s", 
     URLEncoder.encode(param1, charset), 
     URLEncoder.encode(param2, charset));
The query parameters must be in name=value format and be concatenated by &. You would normally also URL-encode the query parameters with the specified charset using URLEncoder#encode().
The String#format() is just for convenience. I prefer it when I would need the String concatenation operator + more than twice.

Firing a HTTP GET request with (optionally) query parameters

It's a trivial task. It's the default request method.
URLConnection connection = new URL(url + "?" + query).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
InputStream response = connection.getInputStream();
// ... 
Any query string should be concatenated to the URL using ?. The Accept-Charset header may hint the server what encoding the parameters are in. If you don't send any query string, then you can leave the Accept-Charset header away. If you don't need to set any headers, then you can even use the URL#openStream() shortcut method.
InputStream response = new URL(url).openStream();
// ... 
Either way, if the other side is a HttpServlet, then its doGet() method will be called and the parameters will be available by HttpServletRequest#getParameter().

Firing a HTTP POST request with query parameters

Setting the URLConnection#setDoOutput() to true implicitly sets the request method to POST. The standard HTTP POST as web forms do is of type application/x-www-form-urlencoded wherein the query string is written to the request body.
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
 
try (OutputStream output = connection.getOutputStream()) {
    output.write(query.getBytes(charset));
} 
 
InputStream response = connection.getInputStream();
// ... 
Note: whenever you'd like to submit a HTML form programmatically, don't forget to take the name=value pairs of any <input type="hidden"> elements into the query string and of course also the name=value pair of the <input type="submit"> element which you'd like to "press" programmatically (because that's usually been used in the server side to distinguish if a button was pressed and if so, which one).
You can also cast the obtained URLConnection to HttpURLConnection and use its HttpURLConnection#setRequestMethod() instead. But if you're trying to use the connection for output you still need to set URLConnection#setDoOutput() to true.
HttpURLConnection httpConnection = (HttpURLConnection) new URL(url).openConnection();
httpConnection.setRequestMethod("POST");
// ... 
Either way, if the other side is a HttpServlet, then its doPost() method will be called and the parameters will be available by HttpServletRequest#getParameter().

Actually firing the HTTP request

You can fire the HTTP request explicitly with URLConnection#connect(), but the the request will automatically be fired on demand when you want to get any information about the HTTP response, such as the response body using URLConnection#getInputStream() and so on. The above examples does exactly that, so the connect() call is in fact superfluous.

Gathering HTTP response information

You need a HttpURLConnection here. Cast it first if necessary.
int status = httpConnection.getResponseCode();
for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
    System.out.println(header.getKey() + "=" + header.getValue());
} 
When the Content-Type contains a charset parameter, then the response body is likely text based and we'd like to process the response body with the server-side specified character encoding then.
String contentType = connection.getHeaderField("Content-Type");
String charset = null;
 
for (String param : contentType.replace(" ", "").split(";")) {
    if (param.startsWith("charset=")) {
        charset = param.split("=", 2)[1];
        break; 
    } 
} 
 
if (charset != null) {
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(response, charset))) {
        for (String line; (line = reader.readLine()) != null;) {
            // ... System.out.println(line) ? 
        } 
    } 
} 
else { 
    // It's likely binary content, use InputStream/OutputStream. 
} 

Maintaining the session

The server side session is usually backed by a cookie. Some web forms require that you're logged in and/or are tracked by a session. You can use the CookieHandler API to maintain cookies. You need to prepare a CookieManager with a CookiePolicy of ACCEPT_ALL before sending all HTTP requests.
// First set the default cookie manager. 
CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
 
// All the following subsequent URLConnections will use the same cookie manager. 
URLConnection connection = new URL(url).openConnection();
// ... 
 
connection = new URL(url).openConnection();
// ... 
 
connection = new URL(url).openConnection();
// ... 
Note that this is known to not always work properly in all circumstances. If it fails for you, then best is to manually gather and set the cookie headers. You basically need to grab all Set-Cookie headers from the response of the login or the first GET request and then pass this through the subsequent requests.
// Gather all cookies on the first request. 
URLConnection connection = new URL(url).openConnection();
List<String> cookies = connection.getHeaderFields().get("Set-Cookie");
// ... 
 
// Then use the same cookies on all subsequent requests. 
connection = new URL(url).openConnection();
for (String cookie : cookies) {
    connection.addRequestProperty("Cookie", cookie.split(";", 2)[0]);
} 
// ... 
The split(";", 2)[0] is there to get rid of cookie attributes which are irrelevant for the server side like expirespath, etc. Alternatively, you could also use cookie.substring(0, cookie.indexOf(';')) instead of split().

Streaming mode

The HttpURLConnection will by default buffer the entire request body before actually sending it, regardless of whether you've set a fixed content length yourself using connection.setRequestProperty("Content-Length", contentLength);. This may cause OutOfMemoryExceptions whenever you concurrently send large POST requests (e.g. uploading files). To avoid this, you would like to set the HttpURLConnection#setFixedLengthStreamingMode().
httpConnection.setFixedLengthStreamingMode(contentLength);
But if the content length is really not known beforehand, then you can make use of chunked streaming mode by setting the HttpURLConnection#setChunkedStreamingMode() accordingly. This will set the HTTP Transfer-Encoding header to chunked which will force the request body being sent in chunks. The below example will send the body in chunks of 1KB.
httpConnection.setChunkedStreamingMode(1024);

User-Agent

It can happen that a request returns an unexpected response, while it works fine with a real web browser. The server side is probably blocking requests based on the User-Agent request header. The URLConnection will by default set it to Java/1.6.0_19 where the last part is obviously the JRE version. You can override this as follows:
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401"); // Do as if you're using Firefox 3.6.3.
Use the User-Agent string from a recent browser.

Error handling

If the HTTP response code is 4nn (Client Error) or 5nn (Server Error), then you may want to read the HttpURLConnection#getErrorStream() to see if the server has sent any useful error information.
InputStream error = ((HttpURLConnection) connection).getErrorStream();
If the HTTP response code is -1, then something went wrong with connection and response handling. The HttpURLConnection implementation is somewhat buggy with keeping connections alive. You may want to turn it off by setting the http.keepAlive system property to false. You can do this programmatically in the beginning of your application by:
System.setProperty("http.keepAlive", "false");

Uploading files

You'd normally use multipart/form-data encoding for mixed POST content (binary and character data). The encoding is in more detail described in RFC2388.
String param = "value";
File textFile = new File("/path/to/file.txt");
File binaryFile = new File("/path/to/file.bin");
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
String CRLF = "\r\n"; // Line separator required by multipart/form-data.
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
 
try ( 
    OutputStream output = connection.getOutputStream();
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
) { 
    // Send normal param. 
    writer.append("--" + boundary).append(CRLF);
    writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);
    writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
    writer.append(CRLF).append(param).append(CRLF).flush();
 
    // Send text file. 
    writer.append("--" + boundary).append(CRLF);
    writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" + textFile.getName() + "\"").append(CRLF);
    writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); // Text file itself must be saved in this charset!
    writer.append(CRLF).flush();
    Files.copy(textFile.toPath(), output);
    output.flush(); // Important before continuing with writer!
    writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
 
    // Send binary file. 
    writer.append("--" + boundary).append(CRLF);
    writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF);
    writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF);
    writer.append("Content-Transfer-Encoding: binary").append(CRLF);
    writer.append(CRLF).flush();
    Files.copy(binaryFile.toPath(), output);
    output.flush(); // Important before continuing with writer!
    writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
 
    // End of multipart/form-data. 
    writer.append("--" + boundary + "--").append(CRLF).flush();
} 
If the other side is a HttpServlet, then its doPost() method will be called and the parts will be available by HttpServletRequest#getPart() (note, thus not getParameter() and so on!). The getPart() method is however relatively new, it's introduced in Servlet 3.0 (Glassfish 3, Tomcat 7, etc). Prior to Servlet 3.0, your best choice is using Apache Commons FileUpload to parse a multipart/form-data request. Also see this answer for examples of both the FileUpload and the Servelt 3.0 approaches.

Dealing with untrusted or misconfigured HTTPS sites

Sometimes you need to connect a HTTPS URL, perhaps because you're writing a web scraper. In that case, you may likely face a javax.net.ssl.SSLException: Not trusted server certificate on some HTTPS sites who doesn't keep their SSL certificates up to date, or a java.security.cert.CertificateException: No subject alternative DNS name matching [hostname] found or javax.net.ssl.SSLProtocolException: handshake alert: unrecognized_nameon some misconfigured HTTPS sites.
The following one-time-run static initializer in your web scraper class should make HttpsURLConnection more lenient as to those HTTPS sites and thus not throw those exceptions anymore.
static { 
    TrustManager[] trustAllCertificates = new TrustManager[] {
        new X509TrustManager() {
            @Override 
            public X509Certificate[] getAcceptedIssuers() { 
                return null; // Not relevant. 
            } 
            @Override 
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
                // Do nothing. Just allow them all. 
            } 
            @Override 
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
                // Do nothing. Just allow them all. 
            } 
        } 
    }; 
 
    HostnameVerifier trustAllHostnames = new HostnameVerifier() {
        @Override 
        public boolean verify(String hostname, SSLSession session) {
            return true; // Just allow them all. 
        } 
    }; 
 
    try { 
        System.setProperty("jsse.enableSNIExtension", "false");
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCertificates, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(trustAllHostnames);
    } 
    catch (GeneralSecurityException e) {
        throw new ExceptionInInitializerError(e);
    } 
} 

Last words

The Apache HttpComponents HttpClient is much more convenient in this all :)

Parsing and extracting HTML

If all you want is parsing and extracting data from HTML, then better use a HTML parser like Jsoup
reffer stackoverflow