import android net Uri import android os AsyncTask import android util

  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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONException;
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.util.HashMap;
import java.util.Map;
import ru.twosphere.android.misisbooks.Edition;
import ru.twosphere.android.misisbooks.MisisBooksDataParser;
/**
* Created by Александр on 25.03.2015.
* Java examples (using AsyncTask and Uri.Builder)
*/
public class TestApiClass {
public void MainTestCase() {
HashMap<String, String> params = new HashMap<>();
params.put("q", "степанова");
params.put("access_token", "ACCESS_TOKEN");
HttpRequestBuilder builder = new HttpRequestBuilder();
builder.setParams(params);
builder.setUri("http://twosphere.ru/api/materials.search");
TestAsyncTask testTask = new TestAsyncTask();
testTask.setRequestMethod(TestAsyncTask.GET_REQUEST_NAME);
testTask.execute(builder.build().getUrl());
}
public class HttpRequestBuilder {
private final String LOG_TAG = HttpRequestBuilder.class.getSimpleName();
private String mReadyUrl;
private String mUri;
private HashMap<String, String> mRequestParams;
public HttpRequestBuilder() {}
public HttpRequestBuilder(HashMap<String, String> params) {
mRequestParams = params;
}
public void setParams(HashMap<String, String> params) {
mRequestParams = params;
}
public void setUri(String uri) {
mUri = uri;
}
public String generateStringUrl() {
try {
Uri.Builder builtUri = Uri.parse(mUri).buildUpon();
for (Map.Entry entry : mRequestParams.entrySet()) {
builtUri = builtUri.appendQueryParameter(entry.getKey().toString(),
entry.getValue().toString());
}
return builtUri.build().toString();
} catch (Exception err) {
Log.e(LOG_TAG, "Error occurred: " + err.getMessage());
return mUri != null ? mUri : "";
}
}
public HttpRequestBuilder build() {
mReadyUrl = generateStringUrl();
return HttpRequestBuilder.this;
}
public URL getUrl() {
try {
return new URL(mReadyUrl);
} catch (MalformedURLException err) {
Log.e(LOG_TAG, "Error occurred: " + err.getMessage());
return null;
}
}
}
public class TestAsyncTask extends AsyncTask<URL, Integer, Edition[]> {
/**
* <String, Void, Edition[]> — URL::String, Progress Report::Integer, Result::Edition[]
*/
private final String LOG_TAG = TestAsyncTask.class.getSimpleName();
public static final String POST_REQUEST_NAME = "POST";
public static final String GET_REQUEST_NAME = "GET";
public static final String HEAD_REQUEST_NAME = "HEAD";
private String mSelectedMethod = POST_REQUEST_NAME;
public void setRequestMethod(String selected) {
if (!selected.equals(POST_REQUEST_NAME) && !selected.equals(GET_REQUEST_NAME) &&
!selected.equals(HEAD_REQUEST_NAME)) {
return;
}
mSelectedMethod = selected;
}
@Override
protected void onPreExecute() {
// выполнение кода в UI потоке до запуска HTTP запроса
}
@Override
protected void onProgressUpdate(Integer... values) {
// Обновите индикатор хода выполнения, уведомления или другой
// элемент пользовательского интерфейса.
// Выполняется в UI потоке после каждого изменения
}
protected Edition[] doInBackground(URL... urls) {
// Выполняется не в UI потоке. Создается отдельный поток с помощью менеджера.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String responseJsonStr = null;
try {
URL url = urls[0];
// Create the request to MISIS Books, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod(mSelectedMethod);
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
responseJsonStr = buffer.toString();
MisisBooksDataParser misisBooksDataParser = new MisisBooksDataParser();
return misisBooksDataParser.getEditionsFromResponse(responseJsonStr);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the misis books data, there's no point in attempting
// to parse it.
return null;
} catch (final JSONException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the misis books data, there's no point in attempting
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
}
@Override
protected void onPostExecute(Edition[] editions) {
Log.d(LOG_TAG, "[onPostExecute] Response has been received");
// Сюда приходит ответ после завершения HTTP запроса
// Выполняется в UI потоке
}
}
}