Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.net.*;
- import java.security.cert.Certificate;
- import java.io.*;
- import java.util.List;
- import java.util.Map;
- import java.util.HashMap;
- public class HttpFetcher {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- HttpFetcher http = new HttpFetcher();
- String postData = "user=user1234&password=pass1234";
- String html = "";
- //Build request headers
- RequestHeaders request = new RequestHeaders();
- request.set("Content-Type", "application/x-www-form-urlencoded");
- request.set("Content-Length", "" + Integer.toString(postData.getBytes().length));
- request.set("Content-Language", "en-US");
- Map<String,List<String>> responseHeaders = new HashMap<String,List<String>>();
- try{
- html = http.executePost("http://foobar.com",postData,request);
- System.out.println(responseHeaders.size());
- if( responseHeaders.containsKey("Set-Cookie")){
- System.out.println("Contains cookie");
- }else{
- System.out.println("Doesn't contain cookie");
- }
- }catch(IOException e){
- System.out.println("IOException");
- }
- //System.out.println(html);
- }
- public static String executePost(String targetURL, String urlParameters,RequestHeaders request) throws IOException {
- URL url;
- HttpURLConnection connection = null;
- try {
- //Create connection
- url = new URL(targetURL);
- connection = (HttpURLConnection)url.openConnection();
- connection.setRequestMethod("POST");
- //Apply request headers
- request.apply(connection);
- 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();
- //Response headers
- responseHeaders = connection.getHeaderFields();
- //System.out.println( responseHeaders.toString() );
- return response.toString();
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- } finally {
- if(connection != null) {
- connection.disconnect();
- }
- }
- }
- private static String get_content(HttpURLConnection con){
- String content = "";
- if(con!=null){
- try {
- BufferedReader br =
- new BufferedReader(
- new InputStreamReader(con.getInputStream()));
- String input;
- while ((input = br.readLine()) != null){
- content += input;
- }
- br.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return content;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement