这是我在这个网站上的第一篇文章,我的应用程序有问题,我无法找到我的应用程序停止的原因。我正在向Despegar发送请求以获得这些国家的json但发生了这些。如果你能帮助我,我会非常感激。这是我的代码:
public class MainActivity extends Activity {
final TextView txtResultado = (TextView) findViewById(R.id.txtResultado);
String JSONRequest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new TareaConexion().execute("http://api.despegar.com/countries");
}
class TareaConexion extends AsyncTask<String, Void, String>{
protected void onPreExecute() {
}
protected String doInBackground(String... urls) {
httpHandler httphandler = new httpHandler();
JSONRequest = httphandler.Post(urls[0]);
return JSONRequest;
}
protected void onProgressUpdate () {
}
protected void onPostExecute() {
txtResultado.setText(JSONRequest);
}
}
和类httpHandler:
public class httpHandler {
public String Post (String PostURL)
{
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(PostURL);
HttpResponse resp = httpclient.execute(httppost);
HttpEntity ent = resp.getEntity();
String Respuesta = EntityUtils.toString(ent);
return Respuesta;
} catch (Exception e) {
return "error";
}
}
}
任何人都可以找到我的应用停止的原因吗?我做错了什么?
我是阿根廷人,请原谅我,如果我用语言,ajja犯了错误。感谢
答案 0 :(得分:1)
试试此代码
MyAsyncTask extends AsyncTask<String, Void, HttpResponse>
{
@Override
protected HttpResponse doInBackground(String... param)
{
String url = param[0];
HttpResponse response = null;
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter("http.connection-manager.timeout", 15000);
try {
if (type == Constants.TYPE_POST)
{
HttpPost httppost = new HttpPost(url);
response = httpclient.execute(httppost);
}
else if (type == Constants.TYPE_DELETE)
{
HttpDelete httpdelete = new HttpDelete(url);
response = httpclient.execute(httpdelete);
}
else
{
HttpGet httppost = new HttpGet(url);
response = httpclient.execute(httppost);
}
} catch (ClientProtocolException es)
{
Log.e("x" , es.getMessage());
} catch (IOException e)
{
Log.e("aasx" , e.getMessage());
}
return response;
}
@Override
protected void onPostExecute(HttpResponse response)
{
if (response != null)
{
JSONObject obj = new JSONObject(Utilities.convertStreamToString(response.getEntity().getContent()));
//Whatever you want to do
}
}
}