1.请求方法不能写在主线程中,要另开启一个线程,在主线程中开启子线程
import java.io.BufferedReader;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new MyThread().start();//启动了我们的线程了
}
class MyThread extends Thread {
public void run() {
// 你要实现的代码
String userId = "1";
String location = "北京市朝阳区";
String startoverTime = "2014-05-29 12:23:25";
String url = "http://*************************************";
String urlString = url + "&userId=" + userId + "&location=" + location
+ "&startoverTime=" + startoverTime;
System.out.println("urlString = " + urlString);
// 生成请求对象
HttpGet httpGet = new HttpGet(url);
HttpClient httpClient = new DefaultHttpClient();
// 发送请求
try {
HttpResponse response = httpClient.execute(httpGet);
System.out.println("response = " + response);
// 显示响应
showResponseResult(response);// 一个私有方法,将响应结果显示出来
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 显示响应结果到命令行
*
* @param response
*/
private void showResponseResult(HttpResponse response) {
if (null == response) {
return;
}
HttpEntity httpEntity = response.getEntity();
try {
InputStream inputStream = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
String result = "";
String line = "";
while (null != (line = reader.readLine())) {
result += line;
}
System.out.println("result =" + result);
// mResult.setText("Response Content from server: " + result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
2.第二种方法HttpConnection
===================================================================================================================
public class HttpConnection {
public static String getHttpRequest(String urlString){
URL url;
InputStream in = null;
HttpURLConnection conn = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
url = new URL(urlString);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setDoInput(true);
conn.connect();
if(conn.getResponseCode() == HttpsURLConnection.HTTP_OK){
in = conn.getInputStream();
int len =0;
byte[] buffer = new byte[1024];
while((len= in.read(buffer))!=-1){
out.write(buffer, 0, len);
}
return out.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(in!=null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(conn!=null){
conn.disconnect();
}
if(out!=null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}