HttpURLConnection编写方法

来源:互联网 发布:网络机柜 编辑:程序博客网 时间:2024/06/05 10:19

public class MainActivity extends Activity {
// String path = "http://op.juhe.cn/onebox/news/query?q=普京盟友炮轰OPEC不团结 称其影响油市的时代已终结&key=f2219bf102195209a3db41a58ce0b180";

 
 String path = "http://web.juhe.cn:8080/constellation/getAll";
 //给服务器传递的参数
 String str="consName=狮子座&type=today&key=3ac9f31ff66b9746539472887b3799c3";

 Handler handler = new Handler() {
  public void handleMessage(android.os.Message msg) {};

 };

 private ListView listView;

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

  listView = (ListView) findViewById(R.id.listView);

  new Thread() {

   public void run() {
    geData();
   };

  }.start();

 }

 /**
  *
  */
 private void geData() {
  // 设置接口地址
  try {
   URL url = new URL(path);
   
   HttpURLConnection connection = (HttpURLConnection) url
     .openConnection();
   
   // 设置连接超时
   connection.setConnectTimeout(5000);
   // 设置读取超时
   connection.setReadTimeout(5000);
   // 设置请求方式
   connection.setRequestMethod("POST");
   
   //得到输出流,象服务器传递参数
   OutputStream outputStream = connection.getOutputStream();
   
   PrintWriter printWriter=new PrintWriter(outputStream);
   //设置要传递的数据
   printWriter.println(str);
   
   printWriter.flush();
   
   // 连接网络
   connection.connect();
   // 如果响应码等于200代表请求成功
   if (connection.getResponseCode() == 200) {
    // 得到服务器返回的信息,是流的形式返回回来的
    InputStream inputStream = connection.getInputStream();
    BufferedReader bufferedReader = new BufferedReader(
      new InputStreamReader(inputStream, "UTF-8"));

    String str;
    StringBuffer stringBuffer = new StringBuffer();
    // 一次读一行
    while ((str = bufferedReader.readLine()) != null) {
     // 把读到的每一行信息都追加到stringBuffer里
     stringBuffer.append(str);
    }

    String data = stringBuffer.toString();
    
//    System.out.println(data);
    
    // 将json数据转成对象
    Gson gson = new Gson();

    Bean bean = gson.fromJson(data, Bean.class);
    
    System.out.println(bean.toString());
    // 把对象通过handler发送给主线程
    Message msg = Message.obtain();
//    msg.obj = root;
//    handler.sendMessage(msg);

   } else {

    Toast.makeText(this, "  请求失败 ", 0).show();

   }

  } catch (MalformedURLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }

}

0 0
原创粉丝点击