【问题标题】:http get in androidhttp 进入安卓
【发布时间】:2012-10-01 08:25:17
【问题描述】:

我有以下 android 代码,我在服务中有一个 sms 广播接收器,它等待收到的短信,然后在接收到它时,它会显示一个 toast,然后它应该向指定的 url 发出 get 请求,一切都按预期工作,但上传消息操作没有发生,在这里被难住了。

public class ReceiverContainer extends Service{

 public SMSreceiver mSMSreceiver;
 public IntentFilter mIntentFilter;

@Override
public void onCreate()
{
    super.onCreate();

    //SMS event receiver
    mSMSreceiver = new SMSreceiver();
    mIntentFilter = new IntentFilter();
    mIntentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
    registerReceiver(mSMSreceiver, mIntentFilter);
}

@Override
public void onDestroy()
{
    super.onDestroy();

    // Unregister the SMS receiver
    unregisterReceiver(mSMSreceiver);
    mSMSreceiver = null;
}

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

public class SMSreceiver extends BroadcastReceiver
{
     public void Action(Context context,Intent intent) throws ClientProtocolException, URISyntaxException, IOException
        {
         Bundle myBundle = intent.getExtras();
         SmsMessage [] messages = null;
         String strMessage = "";
         String msgFrom = "";
         String msgText = "";

         if (myBundle != null)
         {
             Object [] pdus = (Object[]) myBundle.get("pdus");
             messages = new SmsMessage[pdus.length];

             for (int i = 0; i < messages.length; i++)
             {
                 messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                 strMessage += "SMS From: " + messages[i].getOriginatingAddress();
                 msgFrom += messages[i].getOriginatingAddress();
                 strMessage += " : ";
                 strMessage += messages[i].getMessageBody();
                 msgText += messages[i].getMessageBody();
                 strMessage += "\n";
             }

             Toast.makeText(context, strMessage, Toast.LENGTH_SHORT).show();

             uploadMessage(context,msgFrom,msgText);

         }
        }

    @Override
    public void onReceive(Context context, Intent intent)
    {
            try {
                Action(context,intent);
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (URISyntaxException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }

}

public void uploadMessage(Context context,String number,String msg) throws URISyntaxException, ClientProtocolException, IOException
{

    HttpResponse response = null;
    HttpClient client = new DefaultHttpClient();


    Uri.Builder path = new Uri.Builder();
    path.scheme("http");
    path.authority("technonectar11.com");
    path.path("sms");
    path.appendQueryParameter("fromno" , number);
    path.appendQueryParameter("text" , msg);
    path.appendQueryParameter("uname" , "vijay");

    HttpGet request = new HttpGet(path.build().toString());     
    //request.setURI(new URI("http://www.technonectar11.com/sms/insertsms?fromno="+number+"&text="+msg+"&uname=vijay"));
    response = client.execute(request);

    String result = convertStreamToString(response.getEntity().getContent());

    Toast.makeText(context, result, Toast.LENGTH_SHORT).show();

}

public static String convertStreamToString(InputStream inputStream) throws IOException
{
    if (inputStream != null)
    {
        Writer writer = new StringWriter();

        char[] buffer = new char[1024];
        try
        {
            Reader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"),1024);
            int n;
            while ((n = reader.read(buffer)) != -1)
            {
                writer.write(buffer, 0, n);
            }
        }
        finally
        {
            inputStream.close();
        }
        return writer.toString();
    }
    else
    {
        return "";
    }
}

}

【问题讨论】:

    标签: java android http get request


    【解决方案1】:

    您不能在主线程上发出 Internet 请求。 使用AsyncTasks 发出请求。

    【讨论】:

    • 我将它用作服务,它的流程与这里的主要活动不同,我使用了几乎类似的服务在从 http get 请求接收到它后发送短信,它工作正常,但它没有似乎以某种方式在广播接收器的 onReceive 方法中工作
    • 谢谢伙计,我花了很多时间通读 ddms 控制台来得到这个,它给了我一个“NetworkOnMainThreadException”,它不允许我提出那个互联网请求。但我相信 IntentService 确实可以防止这种异常,因为它会创建自己的线程,如 AsyncTasks 或 Handler?
    • 我明白你的意思。你能创建一个 AsyncTask 来完成这个任务吗?
    • 抱歉回复晚了,是的,现在可以了,我用AsyncTask处理网络请求,效果很好,谢谢回复。
    【解决方案2】:

    在最文件中声明 INTERNET 权限

    试试 HttpPost

    httpclient=new DefaultHttpClient();
         HttpPost httppost=new HttpPost(URL);
    
         HttpResponse res = null;
            try {
                res = httpclient.execute(httppost);
                System.out.println("asa "+res);
    
            } catch (ClientProtocolException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            } 
    

    【讨论】:

    • 已经声明了互联网权限,至于接收器,因为我动态使用它,我没有在清单中声明它,但广播接收器工作正常并接收短信,但我无法使用更新它http get 请求,会尝试查看 http post 是否有效
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-27
    • 2014-04-10
    相关资源
    最近更新 更多