httpget

原创 2018年04月15日 15:43:01
package com.http.test01;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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 com.example.test02.R;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

public class HttpActivity extends Activity{

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_http);
		sendRequestWithHttpClient();
	}
	
	private void sendRequestWithHttpClient() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpClient httpCient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet("http://192.168.31.108/");

                try {
                    HttpResponse httpResponse = httpCient.execute(httpGet);
                    if (httpResponse.getStatusLine().getStatusCode() == 200) {
                        HttpEntity entity = httpResponse.getEntity();
                        String response = EntityUtils.toString(entity,"utf-8");
                        Message msg = handler.obtainMessage();
                        msg.obj = response;
                        msg.sendToTarget();
                    }

                } catch (Exception e) {
                    Message msg = handler.obtainMessage();
                    msg.obj = "oh no";
                    msg.sendToTarget();
                }

            }
        }).start();
    }
	
	Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			String response = (String) msg.obj;
            Toast.makeText(HttpActivity.this, "response:"+response, Toast.LENGTH_LONG).show();
		}
	};
}

收藏助手
不良信息举报
您举报文章:httpget
举报原因:
原因补充:

(最多只允许输入30个字)