-1

安卓新手。尝试制作一个简单的应用程序以在按下按钮时对某个站点执行 httpget 请求。按钮有效,祝酒词有效,但执行 httpget 时出现错误。谢谢你的帮助....

这是我所拥有的:

package com.example.impdmxcontroller;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
  }

  public void Ch1on(View view) throws ClientProtocolException, IOException {  
    Toast.makeText(this, "Ch 1 On!", Toast.LENGTH_SHORT).show();  
    try {
      HttpClient client = new DefaultHttpClient();  
      String getURL = "https://www.google.com";
      HttpGet get = new HttpGet(getURL);
      HttpResponse responseGet = client.execute(get);  
      HttpEntity resEntityGet = responseGet.getEntity();  
      if (resEntityGet != null) {  
        //do something with the response
        Log.i("GET RESPONSE",EntityUtils.toString(resEntityGet));
      }
    } catch (Exception e) {
      e.printStackTrace();
    }  
  }  

  public void Ch1off(View view) throws ClientProtocolException, IOException {  
    Toast.makeText(this, "Ch 1 Off!", Toast.LENGTH_SHORT).show();  
    try {
      HttpClient client = new DefaultHttpClient();  
      String getURL = "https://www.google.com";
      HttpGet get = new HttpGet(getURL);
      HttpResponse responseGet = client.execute(get);  
      HttpEntity resEntityGet = responseGet.getEntity();  
      if (resEntityGet != null) {  
        //do something with the response
        Log.i("GET RESPONSE",EntityUtils.toString(resEntityGet));
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }  

  @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;
  }
}
4

1 回答 1

0

HTTP get 在主视图线程中。两种方法来处理它。要么创建一个新线程来运行网络任务,要么在 onCreate() 方法中添加这两行

    StrictMode.ThreadPolicy ourPolicy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(ourPolicy);
于 2013-06-30T03:01:15.587 回答