android http get

package com.example.htmldaimachakanqi;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLEncoder;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends Activity {
	private EditText et_address;
	private EditText et_content;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		et_address = (EditText) findViewById(R.id.et_address);
		et_content = (EditText) findViewById(R.id.et_content);
	}

	public void onClick(View view) throws UnsupportedEncodingException {
		// 获取编辑框输入的网址
		String urlStr = et_address.getText().toString();
		new AsyncTask<String, Void, String>() {
			@Override
			protected String doInBackground(String... params) {
				Log.d("hk",params[0]);
				// 字符串缓冲区
				StringBuffer buffer = new StringBuffer();
				try {
					// 封装了URL对象
					URL url = new URL(params[0] + ":80");
					// 获取http连接对象
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();
					conn.setRequestMethod("GET");
					// 设置连接超时的时间(单位:毫秒)
					conn.setConnectTimeout(5000);
					//设置读取数据的超时时间
					conn.setReadTimeout(5000);
					Log.d("hk", "开始连接服务器。。。");
					try {
						// 连接服务器
						conn.connect();
					} catch (SocketTimeoutException e) {
						return "连接超时";
					}
					Log.d("hk", "成功连接到服务器。。。");
					// 获取状态码
					int code = conn.getResponseCode();
					if (code == 200) {// 请求成功
						Log.d("hk",conn.getHeaderFields().toString());
						// 获取响应消息的实体内容
						InputStreamReader reader = new InputStreamReader(
								conn.getInputStream());
						char[] charArr = new char[1024 * 8];
						int len = 0;
						while ((len = reader.read(charArr)) != -1) {
							// 字符数组转字符串
							String str = new String(charArr, 0, len);
							// 在结尾追加字符串
							buffer.append(str);
						}
					}
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				return buffer.toString();
			}

			protected void onPostExecute(String result) {
				// 设置字符串到编辑框
				et_content.setText(result);
			};
		}.execute("http://gc.ditu.aliyun.com/geocoding?a="+URLEncoder.encode("上海","UTF-8"));
	}
}

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页