I'm making a management software in java for a book store. There is a database on my server. I get my database data by php code.which is also in my server.I use the code below to get data by running the php code.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class HttpUtility {
private static HttpURLConnection httpConn;
public static HttpURLConnection sendGetRequest(String requestURL)
throws IOException {
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoInput(true);
httpConn.setDoOutput(false);
return httpConn;
}
public static HttpURLConnection sendPostRequest(String requestURL,
Map<String, String> params) throws IOException {
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoInput(true);
StringBuffer requestParams = new StringBuffer();
if (params != null && params.size() > 0) {
httpConn.setDoOutput(true);
Iterator<String> paramIterator = params.keySet().iterator();
while (paramIterator.hasNext()) {
String key = paramIterator.next();
String value = params.get(key);
requestParams.append(URLEncoder.encode(key, "UTF-8"));
requestParams.append("=").append(
URLEncoder.encode(value, "UTF-8"));
requestParams.append("&");
}
OutputStreamWriter writer = new OutputStreamWriter(
httpConn.getOutputStream());
writer.write(requestParams.toString());
writer.flush();
}
return httpConn;
}
public static String readSingleLineRespone() throws IOException {
InputStream inputStream = null;
if (httpConn != null) {
inputStream = httpConn.getInputStream();
} else {
throw new IOException("Connection is not established.");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
String response = reader.readLine();
reader.close();
return response;
}
public static String[] readMultipleLinesRespone() throws IOException {
InputStream inputStream = null;
if (httpConn != null) {
inputStream = httpConn.getInputStream();
} else {
throw new IOException("Connection is not established.");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
List<String> response = new ArrayList<String>();
String line = "";
while ((line = reader.readLine()) != null) {
response.add(line);
}
reader.close();
return (String[]) response.toArray(new String[0]);
}
public static void disconnect() {
if (httpConn != null) {
httpConn.disconnect();
}
}
}
Now I'm facing a problem like the image link (don't have enough reputation for the upload)below.There are 3 image link.
before log in
After the log in and before the search query
Another link is in the comment.
After every request making my C:// drive is loosing 10 MB space and I don't know why(Very noob coder sorry.)
Can anyone help me.
Related
I try to send POST data to a Website. But the "login" will not work.
Slowly i dont know why. There are quite a lot of ways to login to a website without browser-ui. What is the "best" method to login here ?
I uses Jsoup and "normal" HttpURLConnection. With Selenium it works fine, but very slow =(
import com.gargoylesoftware.htmlunit.util.Cookie;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.*;
import org.jsoup.nodes.Document;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.*;
import java.util.List;
import java.util.Map;
public class postget {
private static final String USER_AGENT = "Mozilla/5.0";
private static final String GET_URL = "https://de.metin2.gameforge.com/";
private static final String POST_URL = "https://de.metin2.gameforge.com:443/user/login?__token=";//+token
private static final String POST_PARAMS = "username=USERNAME"+"password=PASSWORD";
static final String COOKIES_HEADER = "Set-Cookie";
public static void main(String[] args) throws IOException {
String var = sendGET();
String var1 =var.substring(0,var.indexOf(";"));
String var2 =var.substring(var.indexOf(";")+1,var.indexOf(":"));
String token =var.substring(var.indexOf(":")+1);
//sendPOST(token,cookie);
jsoup(cookie(),token);
}
private static String sendGET() throws IOException {
URL obj = new URL(GET_URL);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String veri1=response.substring(response.indexOf("verify-v1")+20,response.indexOf("verify-v1")+63);
String veri2=response.substring(response.indexOf("verify-v1")+104,response.indexOf("verify-v1")+147);
String token=response.substring(response.indexOf("token")+6,response.indexOf("token")+38);
return (veri1+";"+veri2+":"+token);
} else {
System.out.println("GET request not worked");
return " ";
}
}
private static String cookie() throws IOException{
String realCookie="";
URL obj = new URL(GET_URL);
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
java.net.CookieManager msCookieManager = new java.net.CookieManager();
Map<String, List<String>> headerFields = connection.getHeaderFields();
List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
if (cookiesHeader != null) {
for (String cookie : cookiesHeader) {
msCookieManager.getCookieStore().add(null,HttpCookie.parse(cookie).get(0));
}
}
List<HttpCookie> cookiess = msCookieManager.getCookieStore().getCookies();
if (cookiess != null) {
if (cookiess.size() > 0) {
for (HttpCookie cookie : cookiess) {
realCookie = cookie.toString().substring(cookie.toString().indexOf("=")+1);
return(realCookie);
}
}
}
return(realCookie);
}
private static void sendPOST(String token,CookieManager msCookieManager) throws IOException {
URL obj = new URL(POST_URL+token);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
if (msCookieManager != null) {
List<HttpCookie> cookies = msCookieManager.getCookieStore().getCookies();
if (cookies != null) {
if (cookies.size() > 0) {
for (HttpCookie cookie : cookies) {
String realCookie = cookie.toString().substring(cookie.toString().indexOf("=")+1);
}
con.setRequestProperty("Cookie", StringUtils.join(cookies, ";"));
}
}
}
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
if(response.indexOf("form-login")>0){
System.out.println("NOPE");
}
if(response.indexOf("logout")>0){
System.out.println("YES");
}
} else {
System.out.println("POST request not worked");
}
}
private static void jsoup(String cookie,String token) throws IOException{
Document response = Jsoup.connect("https://de.metin2.gameforge.com/")
.referrer("https://de.metin2.gameforge.com/main/index?__token=5"+token)
.cookie("Cookie","gf-locale=de_DE; _ga=GA1.2.404625572.1501231885; __auc=a02de56115d8864ad2bd7ad8120; pc_idt=ANu-cNegKMzU8CAsBQAHIu1cRlXEEUD1ka6NvJXWqO4sVVaLIsqSFPyZFt8dXHKcrhrB_u2FFdQnD-2vsA377NnVgjkrKn-3qzi5Q3LXbzgnbbmIEir4zYNCddPbjCUg9cVpSU4GP-CvU53XhrQ6_MWP9tOYNdjCqRVIPw; SID="+cookie+"; __utma=96667401.404625572.1501231885.1503225538.1503232069.15; __utmc=96667401; __utmz=96667401.1501247623.3.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)")
//.data("X-DevTools-Emulate-Network-Conditions-Client-Id","c9bbb769-df80-47ff-8e25-e582de026ecc")
.userAgent("Mozilla")
.data("username", "USERNAME")
.data("password", "PASSWORD")
.post();
System.out.println(response);
}
}
}
The var1 and var1 are unnecessary.
They was my first idea to send with my POST.
Here is a picture if the login-form:
And of HttpClient
I am getting an IOException: unexpected end of stream when trying to read the inputStream of an HttpUrlConnection. I have tested with other URL's like http://google.com and added urlConnection.addRequestProperty("User-Agent", "Mozilla/5.0"); testing for an error on another helpful persons advice but no error occurred. My target SDK and buildSDK match. I am fetching results using the same class for other fragments with different URL's without problems. Since trying to change to another API I've come across this problem.
The URL I'm trying to fetch JSON results from - http://eventregistry.org/json/article?query=%7B%22%24query%22%3A%7B%22%24and%22%3A%5B%7B%22sourceUri%22%3A%7B%22%24and%22%3A%5B%22bbc.co.uk%22%5D%7D%7D%2C%7B%22lang%22%3A%22eng%22%7D%5D%7D%7D&action=getArticles&apikey=342f5f25-75ac-44b5-8da0441508e871e8&resultType=articles&articlesSortBy=date&articlesCount=10&articlesIncludeArticleImage=true
My code to fetch the JSON -
package com.example.android.greennewswire;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
public final class QueryUtils {
private static final String LOG_TAG = QueryUtils.class.getSimpleName();
private QueryUtils(){
}
public static ArrayList<News> fetchNewsData(String requestUrl) {
URL url = createUrl(requestUrl);
String jsonResponse = null;
try {String testString = readUrl(requestUrl); Log.i(LOG_TAG, "testString: " + testString);
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
Log.e(LOG_TAG, "Error making HTTP request", e);
}
if (jsonResponse == null) {
return new ArrayList<News>();
}
ArrayList<News> news = extractBooks(jsonResponse);
return news;
}
public static URL createUrl(String stringUrl){
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Malformed URL", e);
} return url;
}
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = null;
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
InputStream errorStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(10000);
urlConnection.addRequestProperty("User-Agent", "Mozilla/5.0");
urlConnection.connect();
Log.e(LOG_TAG, "Response code: " + urlConnection.getResponseCode());
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromInputStream(inputStream);
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
String string = e.getCause().toString();
Log.e(LOG_TAG, "Problem reading from input stream, " + string, e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
} if (inputStream != null) {
inputStream.close();
}
}
return jsonResponse;
}
private static String readFromInputStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
Stack trace
Problem reading from input stream, java.io.EOFException: \n not found: size=14639 content=7b2261727469636c6573223a7b22726573756c7473223a5b7b226964223a2231...
java.io.IOException: unexpected end of stream on Connection{eventregistry.org:80, proxy=DIRECT# hostAddress=185.49.3.27 cipherSuite=none protocol=http/1.1} (recycle count=0)
at com.android.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:210)
at com.android.okhttp.internal.http.HttpTransport.readResponseHeaders(HttpTransport.java:80)
at com.android.okhttp.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:905)
at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:789)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:443)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:388)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:501)
When I pass the URL "http://echo.jsontest.com/key/value/one/two" to the code below it returns JSON data.
But when I pass "http://jsonplaceholder.typicode.com/comments?postId=1" instead, I get 403 forbidden error.
I'm not sure what's going on. Any advice?
package automation_Demo_First;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
import org.testng.annotations.Test;
public class JsonReader{
//http://jsonplaceholder.typicode.com/comments?postId=1
public String url ="http://echo.jsontest.com/key/value/one/two";
#Test
public void testJson() throws IOException{
String data = getDataByJavaIO(url);
System.out.println(data);
}
public String getDataByJavaIO(String url) throws IOException{
InputStream inputstream = null;
BufferedReader bufferreader = null;
try{
inputstream = new URL(url).openStream();
bufferreader = new BufferedReader(new InputStreamReader(inputstream, Charset.forName("UTF-8")));
return readData(bufferreader);
}catch(IOException e){
throw e;
}
finally{
closeResource(inputstream);
closeResource(bufferreader);
}
}
public String readData(Reader reader) throws IOException{
StringBuilder stringbuilder = new StringBuilder();
int cp;
while((cp=reader.read())!=-1){
stringbuilder.append((char)cp);
}
return stringbuilder.toString();
}
public void closeResource(AutoCloseable closable){
try{
if(closable!=null){
closable.close();
System.out.println("\n" +closable.getClass().getName() + "closed ..." );
}
}
catch(Exception e){
e.printStackTrace(System.err);
}
}
}
In your try block,
try {
inputstream = new URL(url).openStream();
bufferreader = new BufferedReader(new InputStreamReader(inputstream, Charset.forName("UTF-8")));
return readData(bufferreader);
}
change it to
try {
HttpURLConnection httpCon = (HttpURLConnection) new URL(url).openConnection();
httpCon.addRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36");
inputstream = httpCon.getInputStream();
bufferreader = new BufferedReader(new InputStreamReader(inputstream, Charset.forName("UTF-8")));
return readData(bufferreader);
}
Source: https://stackoverflow.com/a/18889991/3903483
Use:
URLConnection hc = new URL(url).openConnection();
hc.setRequestProperty("User-Agent", "");
inputstream = hc.getInputStream();
Instead of:
inputstream = new URL(url).openStream();
I am trying to read source code from a webpage. My java code is
import java.net.*;
import java.io.*;
import java.util.*;
import javax.swing.JOptionPane;
class Testing{
public static void Connect() throws Exception{
URL url = new URL("http://excite.com/education");
URLConnection spoof = url.openConnection();
spoof.setRequestProperty( "User-Agent", "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0; H010818)" );
BufferedReader in = new BufferedReader(new InputStreamReader(spoof.getInputStream()));
String strLine = "";
while ((strLine = in.readLine()) != null){
System.out.println(strLine);
}
System.out.println("End of page.");
}
public static void main(String[] args){
try{
Connect();
}catch(Exception e){
}
}
When i compile and run this code, it gives the following output:
�I�%&/m�{J�J��t�$ؐ#������iG#)�*��eVe]f#�흼��{���{���;�N'���?\fdl��J�ɞ!���?~|?"~�$}�>�������4�����7N�����+�ӲM�N��?J�tZfM��G�j����R��!�9�?>JgE��Ge[����ⳏ���W�?�����8������
�|8�
���������ho����0׳���|փ:--�|�L�Uο���m�zt�n3��l\�w��O^f�G[�CG<�y6K��gM�rg��ǟy�Eִy����h˜��ؗ˲X���l=�ڢZ�/����(կ^O�UU6�����&�6_�#yC}�p�y���lAH�ͯ��zF#�V�6_��}��)�v=J+�$��̤�G�Y�L�b���wS"�7�y^����Z�m���Y:ɛ���J<N_�Y=���U�f���,���y�Q2(J٩P!ͨ�i����1&F0&ૼn�?�x�T��h�Qzw�+����n�)�h��K��2����8g����⮥��A0
���1I�%����Q�Z����{��������w���?x����N�?�<d�S��۫�%a|4�j��z���k�Bak��k-�c�z�g��z���l>���֎s^,��5��/B�{����]]����Ý�ֳ���y{�_l�8g�k�ӫ�b���"+|��(��M��^[���J�P��_�..?������x�Z�$������E>��느�u���E~����{媘���f�e1ͷ�QZ,�����f��e�3Jٻb�^��4��۴���>��y��;��<렛{�l��ZfW
S# {�]��1��Q�����n[�,t�?����~�n�S�u#SL��n�^��������EC��q�/�y���FE�tpm������e&��oB���z9eY��������P��IK?����̦����w�N��;�;J?����;�/��5���M���rZ��q��]��C�dᖣ��F�nd���}���A5���M�5�.�:��/�_D�?�3����'�c�Z7��}��(OI),ۏi����{�<�w�������DZ?e����'q���eY]=���kj���߬������\qhrRn���l�o-��.���k��_���oD8��GA�P�r��|$��ȈPv~Y�:�[q?�sH�� <��C��ˬ�^N�[ v(��S��l�c�C����3���E5&5�VӪL�T��۔���oQrĈ��/���#[f�5�5"����[���t�vm�\��.0�nh����aڌWYM
^T�|\,��퓜�L�u����B�̌�C�r������ �������'�%�{��)�);�fV�]��g,�>�C �c2���p�4��}H���P��(�%j"�}�&�:�Oh\5I�l�氪��{�/�]�LB�l��2��I"��=��Y�|�>�֏n�������}�����~�[��'��O��
��:/�)�Wz�3��lo�.5�k�&����H[ji�����b������WWy}�5�֝Q�|f�����]�KjH5��}yNm�����g�ӷ�ǣ��>��'o��泏��<���G�g���>->�xQM�����%<�|����u�.��3���[�[r���ٝ;���]4E��6[����]����1���*�8}��n�w�������ݽ����|����}|qo|�~u����w|�i�i���Z�`z�ŧ����Q}�u��!���w �O���R9�)�~��g~w6��{���wd�o��/Z�uUS��݄l��I^�����>��[�U1�o�_��J��}��#�#�U�/��/?���i�7|CZT?(�2b~����c�W�c5'����EeFĿꇙ�0��T��{��W�2����/���O���YJj����K/���>��:'_l�
Other than URLs from this directory i.e. "excite.com/education" all URLs are giving correct source codes but these URLs are creating problems.
Anyone Please Help.
Thanks in advance.
It works for me.
private static String getWebPabeSource(String sURL) throws IOException {
URL url = new URL(sURL);
URLConnection urlCon = url.openConnection();
BufferedReader in = null;
if (urlCon.getHeaderField("Content-Encoding") != null
&& urlCon.getHeaderField("Content-Encoding").equals("gzip")) {
in = new BufferedReader(new InputStreamReader(new GZIPInputStream(
urlCon.getInputStream())));
} else {
in = new BufferedReader(new InputStreamReader(
urlCon.getInputStream()));
}
String inputLine;
StringBuilder sb = new StringBuilder();
while ((inputLine = in.readLine()) != null)
sb.append(inputLine);
in.close();
return sb.toString();
}
Try reading it this way:
private static String getUrlSource(String url) throws IOException {
URL url = new URL(url);
URLConnection urlConn = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
urlConn.getInputStream(), "UTF-8"));
String inputLine;
StringBuilder a = new StringBuilder();
while ((inputLine = in.readLine()) != null)
a.append(inputLine);
in.close();
return a.toString();
}
and set your encoding according to the web page - notice this line:
BufferedReader in = new BufferedReader(new InputStreamReader(
urlConn.getInputStream(), "UTF-8"));
First you have to uncompress the content using GZIPInputStream. Then put the uncompressed stream to Input Stream and read it using BufferedReader
Use Apache HTTP Client 4.1.1
Maven dependency
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.1.1</version>
</dependency>
Sample Code to parse gzip content.
package com.gzip.simple;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class GZIPFetcher {
public static void main(String[] args) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet getRequest = new HttpGet("http://excite.com/education");
getRequest.addHeader("accept", "application/json");
HttpResponse response = httpClient.execute(getRequest);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
InputStream instream = response.getEntity().getContent();
// Check whether the content-encoding is gzip or not.
Header contentEncoding = response
.getFirstHeader("Content-Encoding");
if (contentEncoding != null
&& contentEncoding.getValue().equalsIgnoreCase("gzip")) {
instream = new GZIPInputStream(instream);
}
BufferedReader in = new BufferedReader(new InputStreamReader(
instream));
String content;
System.out.println("Output from Server .... \n");
while ((content = in.readLine()) != null)
System.out.println(content);
httpClient.getConnectionManager().shutdown();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I am writing a small java program/api to programatically login/ (do a hthp post with login credentials) to this http://web2sms.ke.airtel.com
For me to post, I need parameter(key and value for the login form). When I render the form via browser, the key/name keep changing everytime to but when I fetch the page via java code below the key is always contact f_1.number, therefore meaning the server in my thinking the server is differentiating if a page is fetched from from a browser or not. How can I simulate a browser and get the figures to be rendered by browser?
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
*
* #author Dell
*/
public class AirtelWeb2Sms {
String link = "http://web2sms.ke.airtel.com";
/**
* #param args the command line arguments
*/
private boolean on = false;
public static void main(String[] args) {
new AirtelWeb2Sms();
}
public AirtelWeb2Sms() {
login();
}
private void login(){
Map <String, String> parameters = new HashMap();
try{
URL url = new URL(link);
URLConnection yc = url.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
if(inputLine.contains("<div id=\"loginform\">"))
{
on=true;
}
if(on && (inputLine.contains("input")||inputLine.contains("select"))&& inputLine.contains("name")&& inputLine.contains("value")){
// System.out.println(inputLine);
String[] tokens = inputLine.split("\" ");
String key="", value="";
for(String str: tokens){
if(str.contains("name=")){
key=str.substring(str.indexOf("\"")+1);
}
if(str.startsWith("value")){
value=str.substring(str.indexOf("\"")+1);
}
if(key.contains(".number")){
value="+25473DummyNumber";
}
if(key.contains(".passwd")){
value="dymmerPassword";
}
if(key.contains(".language")){
value="en";
}
}
parameters.put(key, value=value.replace(""", "\""));
System.out.println(key+":"+value);
}
if(inputLine.contains("<input type=\"submit\""))
{
on=false;
}
}
doSubmit(link+"index.hei", parameters);
}
catch(Exception ex){
System.out.println(ex.getLocalizedMessage());
}
}
public void doSubmit(String url, Map<String, String> data) throws Exception
{
URL siteUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) siteUrl.openConnection();
conn.setRequestMethod("POST"); conn.setDoOutput(true);
conn.setDoInput(true); DataOutputStream out = new DataOutputStream(conn.getOutputStream());
Set keys = data.keySet();
Iterator keyIter = keys.iterator(); String content = "";
for(int i=0; keyIter.hasNext(); i++) {
Object key = keyIter.next();
if(i!=0) {
content += "&";
}
content += key + "=" +data.get(key);
}
System.out.println(content);
out.writeBytes(content);
out.flush();
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
while((line=in.readLine())!=null) {
System.out.println(line); } in.close();
}
}
Try setting the "User-Agent" HTTP header to some value that a real browser would send. You can check what's your browser's user-agent string by visiting http://whatsmyuseragent.com/.