Android: получение кодов состояния HTTP с помощью DefaultHttpClientAndroid

Форум для тех, кто программирует под Android
Ответить
Anonymous
 Android: получение кодов состояния HTTP с помощью DefaultHttpClient

Сообщение 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);
}
}


Подробнее здесь: https://stackoverflow.com/questions/281 ... httpclient
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»