简体   繁体   中英

Android Simple HTTP Request?

I have this code for an Android application I'm trying to create into interact with my PHP website. I have the android.permission.INTERNET permission activated and it keeps creating a toast that says "ERROR." instead of the contents of the website. Here is my only java file:

package com.http.request;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;

public class HttprequestActivity extends Activity {
    /** Called when the activity is first created. */

    private String doHTTPRequest(String url){
        String results = "ERROR";
        try
        {
            HttpClient hc = new DefaultHttpClient();
            HttpPost post = new HttpPost(url);

            HttpResponse rp = hc.execute(post);

            if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
            {
                results = EntityUtils.toString(rp.getEntity());
            }
        }catch(IOException e){
            e.printStackTrace();
        }
        return results;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        String results = doHTTPRequest("http://www.yahoo.com");
        Toast.makeText(getApplicationContext(), results, Toast.LENGTH_LONG).show();
    }
}

I would check to make sure that,

  1. If there is an exception being thrown, investigate what is causing the IOException
  2. Your server could potentially be returning a non-200 response code.

Put in some breakpoints and see whats happening there. My bet is on the response code.

That is your own "ERROR" string which the Toast() displays. Better change

catch(IOException e){
        e.printStackTrace();
    }

to

catch(IOException e){
        result = "ERROR IOException";
        e.printStackTrace();
    }

The exception is thrown as you try to connect in the main thread which is not permitted. Put doHTTPRequest() in a thread or AsyncTask .

What is your stacktrace says, LogCat? What is the error? Add more info, make it more clear to understand than "guessing of coffee beans"

My guess is: this happens because you are trying to do network operation in UI thread which is not allowed in 3.0+ versions. http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM