Java - Consulta-> Manipular Web con HttpClient

 
Vista:
sin imagen de perfil

Consulta-> Manipular Web con HttpClient

Publicado por Jose (1 intervención) el 17/10/2015 01:20:04
Hola a todos,

Soy nuevo en este foro, no conozco muy bien las reglas, si hago o digo algo inapropiado por favor decirme, gracias.

Tengo un pequeño o mas bien gran problema con un aplicativo que estoy desarrollando espero me puedan ayudar y así este tema le pueda ser de solución a otras personas.

Les explico, debo desarrollar un aplicativo de escritorio para una empresa, no voy a explicar todos los requerimientos por obvias razones, el lio que tengo es que debo obtener diferentes datos de una web externa para alimentar la base de datos y eso lo realice constantemente, de la web se deben descargar varios archivos de excel y luego dichos archivos se deben enviar a la base de datos para asi ser manipulados.

El cliente quiere que sea invisible el proceso de descarga del archivo excel y envio a la base de datos
ademas quiere que sea constante la actualización para que los datos siempre estén actualizados.
la pagina pide usuario y contraseña y hay que seguir rutas diferentes y el llenado de formulario de fecha y otros datos para la descarga del los archivos.

he estado utilizando URLconection pero no pude realizar la conección
ahora estoy utilizando HttpConection de Apache, me logro conectar pero no he podido realizar la validación de usuario y contraseña.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
package prueba;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.util.ArrayList;
import java.util.List;
 
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
 
public class HttpCilentExample {
 
  private String cookies;
  private final HttpClient client = HttpClientBuilder.create().build();
  private final String USER_AGENT = "Mozilla/5.0";
 
  public static void main(String[] args) throws Exception {
 
	String url = "http://moduloagenda.cable.net.co/";
	String gmail = "http://moduloagenda.cable.net.co/Informes/AdmonInformes/InterfazInformes.php";
 
	// make sure cookies is turn on
	CookieHandler.setDefault(new CookieManager());
        HttpCilentExample http = new HttpCilentExample();
        String page = http.GetPageContent(url);
        //System.out.println(page);
 
	List<NameValuePair> postParams = http.getFormParams(page, "user","pass");
 
        http.sendPost(url, postParams);
 
	String result = http.GetPageContent(gmail);
	//System.out.println(result);
 
	System.out.println("Done");
  }
 
  private void sendPost(String url, List<NameValuePair> postParams) throws Exception {
 
	HttpPost post = new HttpPost(url);
 
	// add header
	post.setHeader("Host", "moduloagenda.cable.net.co");
	//post.setHeader("User-Agent", USER_AGENT);
	post.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
	post.setHeader("Accept-Language", "en-US,en;q=0.5");
	post.setHeader("Cookie", getCookies());
	post.setHeader("Connection", "keep-alive");
	post.setHeader("Referer", "http://moduloagenda.cable.net.co/index.php");
	post.setHeader("Content-Type", "application/x-www-form-urlencoded");
 
	post.setEntity(new UrlEncodedFormEntity(postParams));
 
	HttpResponse response = client.execute(post);
 
	int responseCode = response.getStatusLine().getStatusCode();
 
	//System.out.println("\nSending 'POST' request to URL : " + url);
	//System.out.println("Post parameters : " + postParams);
	//System.out.println("Response Code : " + responseCode);
 
	BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
 
	StringBuffer result = new StringBuffer();
	String line = "";
	while ((line = rd.readLine()) != null) {
		result.append(line);
	}
 
	 System.out.println(result.toString());
 
  }
 
  private String GetPageContent(String url) throws Exception {
 
	HttpGet request = new HttpGet(url);
 
	request.setHeader("User-Agent", USER_AGENT);
	request.setHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
	request.setHeader("Accept-Language", "en-US,en;q=0.5");
        HttpResponse response = client.execute(request);
	int responseCode = response.getStatusLine().getStatusCode();
        //System.out.println("\nSending 'GET' request to URL : " + url);
	//System.out.println("Response Code : " + responseCode);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer result = new StringBuffer();
	String line = "";
	while ((line = rd.readLine()) != null) {
		result.append(line);
	}
 
	// set cookies
	setCookies(response.getFirstHeader("Set-Cookie") == null ? "" :
                     response.getFirstHeader("Set-Cookie").toString());
 
	return result.toString();
 
  }
 
  public List<NameValuePair> getFormParams(String html, String username, String password) throws UnsupportedEncodingException {
        //System.out.println("Extracting form's data...");
        Document doc = Jsoup.parse(html);
        // Google form id
	Element loginform = doc.getElementById("Registro");
 
 
	//Elements inputElements = loginform.getElementsByTag("input");
        Elements inputElements = loginform.getElementsByClass("tableLogin1");
        List<NameValuePair> paramList = new ArrayList<>();
 
        inputElements.stream().forEach((inputElement) -> {
            String key = inputElement.attr("name");
            System.out.println(key);
            String value = inputElement.attr("value");
            System.out.println(value);
 
            switch (key) {
                case "nv73pBGxlt":
                    value = username;
                    break;
                case "6bupkDzC7E4":
                    value = password;
                    break;
            }
 
 
 
            paramList.add(new BasicNameValuePair(key, value));
      });
 
	return paramList;
  }
 
  public String getCookies() {
	return cookies;
  }
 
  public void setCookies(String cookies) {
	this.cookies = cookies;
  }
 
}


espero me puedan ayudar, si necesitan mas información solamente me escriben :)

GRACIAS.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder