Я новичок в разработке для Android. Я пытаюсь написать небольшое приложение, которое печатает код состояния HTTP запрошенного URL-адреса.
Для любого действительного запроса URL-адреса я получаю 200 (как и ожидалось). . но когда я запрашиваю несуществующий URL-адрес, я получаю 0 (вместо кода ошибки HTTP). Это то, что я вижу из logcat-
System.err java.net.UnknownHostException: невозможно разрешить хост
"www .adsxgp.com": адрес не связан с именем хоста.
Что мне здесь не хватает?
Это мой код-
public class MainActivity extends Activity {
private static String logtag = "TwoButtonApp";//for use as the tag when logging
private TextView textView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.TextBox01);
}
private class CloudLookup extends AsyncTask{
@Override
protected String doInBackground(String... urls) {
// TODO Auto-generated method stub
int responseCode = 0;
for (String url : urls){
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
responseCode = execute.getStatusLine().getStatusCode();
/*
URL obj = new URL(urls[0]);
con = (HttpURLConnection)obj.openConnection();
con.setRequestMethod("GET");
String USER_AGENT= "Mozilla/5.0";
con.setRequestProperty("User-Agent", USER_AGENT);
responseCode = con.getResponseCode(); */
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return Integer.toString(responseCode);
}
@Override
protected void onPostExecute(String result){
Toast.makeText(MainActivity.this, "Yo! I was called!" +result, Toast.LENGTH_LONG).show();
}
}
public void onClick(View view) {
CloudLookup cl = new CloudLookup();
cl.execute(new String[]{"http://www.adsxgp.com"});
Log.d(logtag,"onClick() called");
}
@Override
protected void onStart() {//activity is started and visible to the user
Log.d(logtag,"onStart() called");
super.onStart();
}
@Override
protected void onResume() {//activity was resumed and is visible again
Log.d(logtag,"onResume() called");
super.onResume();
}
@Override
protected void onPause() { //device goes to sleep or another activity appears
Log.d(logtag,"onPause() called");//another activity is currently running (or user has pressed Home)
super.onPause();
}
@Override
protected void onStop() { //the activity is not visible anymore
Log.d(logtag,"onStop() called");
super.onStop();
}
@Override
protected void onDestroy() {//android has killed this activity
Log.d(logtag,"onDestroy() called");
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Подробнее здесь: https://stackoverflow.com/questions/281 ... httpclient
Android: получение кодов состояния HTTP с помощью DefaultHttpClient ⇐ Android
Форум для тех, кто программирует под Android
-
Anonymous
1735229706
Anonymous
Я новичок в разработке для Android. Я пытаюсь написать небольшое приложение, которое печатает код состояния HTTP запрошенного URL-адреса.
Для любого действительного запроса URL-адреса я получаю 200 (как и ожидалось). . но когда я запрашиваю несуществующий URL-адрес, я получаю 0 (вместо кода ошибки HTTP). Это то, что я вижу из logcat-
System.err java.net.UnknownHostException: невозможно разрешить хост
"www .adsxgp.com": адрес не связан с именем хоста.
Что мне здесь не хватает?
Это мой код-
public class MainActivity extends Activity {
private static String logtag = "TwoButtonApp";//for use as the tag when logging
private TextView textView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.TextBox01);
}
private class CloudLookup extends AsyncTask{
@Override
protected String doInBackground(String... urls) {
// TODO Auto-generated method stub
int responseCode = 0;
for (String url : urls){
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
responseCode = execute.getStatusLine().getStatusCode();
/*
URL obj = new URL(urls[0]);
con = (HttpURLConnection)obj.openConnection();
con.setRequestMethod("GET");
String USER_AGENT= "Mozilla/5.0";
con.setRequestProperty("User-Agent", USER_AGENT);
responseCode = con.getResponseCode(); */
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return Integer.toString(responseCode);
}
@Override
protected void onPostExecute(String result){
Toast.makeText(MainActivity.this, "Yo! I was called!" +result, Toast.LENGTH_LONG).show();
}
}
public void onClick(View view) {
CloudLookup cl = new CloudLookup();
cl.execute(new String[]{"http://www.adsxgp.com"});
Log.d(logtag,"onClick() called");
}
@Override
protected void onStart() {//activity is started and visible to the user
Log.d(logtag,"onStart() called");
super.onStart();
}
@Override
protected void onResume() {//activity was resumed and is visible again
Log.d(logtag,"onResume() called");
super.onResume();
}
@Override
protected void onPause() { //device goes to sleep or another activity appears
Log.d(logtag,"onPause() called");//another activity is currently running (or user has pressed Home)
super.onPause();
}
@Override
protected void onStop() { //the activity is not visible anymore
Log.d(logtag,"onStop() called");
super.onStop();
}
@Override
protected void onDestroy() {//android has killed this activity
Log.d(logtag,"onDestroy() called");
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/28179432/android-getting-http-status-codes-using-defaulthttpclient[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия