Академический Документы
Профессиональный Документы
Культура Документы
Отчёт
PAM
Лабораторная работа №3
Тема: Простой HTTP клиент
Кишинёв-2017
Цель работы
Задание:
Теоретические сведения
HTTP (HyperText Transfer Protocol) — протокол передачи данных в виде документов разметки
в формате «HTML». Основой HTTP является технология «клиент-сервер», то есть
предполагается существование:
- Клиентов, которые инициируют соединение и посылают запрос;
- Серверов, которые ожидают соединения для получения запроса, производят необходимые
действия и возвращают обратно сообщение с результатом.
Клиенты:
Первоначально, протокол HTTP разрабатывался для доступа к гипертекстовым документам
Всемирной паутины. Поэтому основными реализациями клиентов являются браузеры (агенты
пользователя).
Серверы:
Основные реализации: Apache, IIS, Google Web Server.
Структурно, каждое HTTP-сообщение состоит из трёх частей, которые передаются в
указанном порядке:
/*
1. onPreExecute(), invoked on the UI thread before the task is executed.
This step is normally used to setup the task, for instance by showing
a progress bar in the user interface.
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
}
/*
2. doInBackground(Params...), invoked on the background thread
immediately after onPreExecute() finishes executing. This step is
used to perform background computation that can take a long time.
The parameters of the asynchronous task are passed to this step.
The result of the computation must be returned by this step and
will be passed back to the last step. This step can also use
publishProgress(Progress...) to publish one or more units of progress.
These values are published on the UI thread, in the
onProgressUpdate(Progress...) step.
*/
@Override
protected Void doInBackground(Void... params) {
String input = "";
try {
//adress of the page with sms
url = new URL(urls + "sendsms");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new
BufferedInputStream(urlConnection.getInputStream());
input = readStream(in);
urlConnection.disconnect();
}catch (Exception e){
e.getStackTrace();
}
try {
captcha_sid = input.substring(input.indexOf("input type=\"hidden\"
name=\"captcha_sid\" value=\"")+46,input.indexOf("input type=\"hidden\"
name=\"captcha_sid\" value=\"")+46+8);
captcha_token = input.substring(input.indexOf("input type=\"hidden\"
name=\"captcha_token\" value=\"")+48,input.indexOf("input type=\"hidden\"
name=\"captcha_token\" value=\"")+48+32);
form_build_id = input.substring(input.indexOf("input type=\"hidden\"
name=\"form_build_id\" value=\"")+48,input.indexOf("input type=\"hidden\"
name=\"form_build_id\" value=\"")+48+48);
Log.d("captcha_sid:", captcha_sid);
Log.d("captcha_token:", captcha_token);
Log.d("form_build_id:", form_build_id);
//adress of captcha
int index = input.indexOf("/rom/private/image_captcha?sid");
src = input.substring(index, index + 61);
Log.d("Image", src);
URL urlPic = new URL(urls + src);
URLConnection conn = urlPic.openConnection();
bitmap = BitmapFactory.decodeStream(conn.getInputStream());
} catch (Exception e) {
e.getStackTrace();
}
publishProgress(bitmap);
return null;
}
/*
3. onProgressUpdate(Progress...), invoked on the UI thread after
a call to publishProgress(Progress...). The timing of the execution
is undefined. This method is used to display any form of progress
in the user interface while the background computation is still
executing. For instance, it can be used to animate a progress bar
or show logs in a text field.
*/
@Override
protected void onProgressUpdate(Bitmap... values) {
super.onProgressUpdate(values);
Image.setImageBitmap(values[0]);
}
/*
4. onPostExecute(Result), invoked on the UI thread after the
background computation finishes. The result of the background
computation is passed to this step as a parameter.
*/
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}