在android应用程序中,可以使用HttpURLConnection发送HTTP请求。详见如下实例

1、activity_main.xml布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"     android:orientation="vertical"    ><Button     android:id="@+id/send_request"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:text="发送请求"    /><ScrollView     android:layout_width="match_parent"    android:layout_height="match_parent"    >    <TextView         android:id="@+id/content"        android:layout_width="match_parent"        android:layout_height="wrap_content"        />    </ScrollView></LinearLayout>
2、MainActivity.java

package com.example.testhttp;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;public class MainActivity extends Activity implements OnClickListener{private Button sendRequest;private TextView content;private static final int SHOW_RESPONSE_CONTENT = 0;private Handler handler = new Handler(){public void handleMessage(Message msg) {switch (msg.what) {case SHOW_RESPONSE_CONTENT:String response = (String) msg.obj;//显示到界面上content.setText(response);break;default:break;}};};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//获取发送按钮sendRequest = (Button) findViewById(R.id.send_request);//获取TextViewcontent = (TextView) findViewById(R.id.content);sendRequest.setOnClickListener(this);}//重写点击方法@Overridepublic void onClick(View view) {if(view.getId() == R.id.send_request){//如果是点击发送按钮,则处理Http请求--使用HttpURLConnectionsendRequestWithHttpURLConnection();}}/** * 使用HttpURLConnection发送请求 */public void sendRequestWithHttpURLConnection(){//新起一线程new Thread(new Runnable() {//处理逻辑@Overridepublic void run() {HttpURLConnection connection = null;try {URL url = new URL("http://www.baidu.com");connection = (HttpURLConnection) url.openConnection();//设置参数//发送请求connection.setRequestMethod("GET");//连接超时时间connection.setConnectTimeout(5000);InputStream in = connection.getInputStream();//对服务器返回的输入流进行读取BufferedReader reader = new BufferedReader(new InputStreamReader(in));StringBuilder builder = new StringBuilder();String line;while((line = reader.readLine())!=null){builder.append(line);}//使用MessageMessage message = new Message();message.what = SHOW_RESPONSE_CONTENT;message.obj = builder.toString();handler.sendMessage(message);} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally{if(connection!=null){//断开连接connection.disconnect();}}}}).start();}@Overridepublic 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;}}
3、获取网络访问权限

修改AndroidManifest.xml,添加:

<uses-permission android:name="android.permission.INTERNET"/>
4、结果

点击发送按钮,如下所示:

这就是服务器返回给我吗的Html代码。


如果是发送数据给服务器呢?看如下代码:

connection.setRequestMethod("POST");DataOutputStream out = new DataOutputStream(connection.getOutputStream());out.writeBytes("username=yy&password=admin");


此外,可以使用HttpClient发送Http请求,

其他不变,在MainActivity.java类中添加方法sendRequestWithHttpClient,如下:

private void sendRequestWithHttpClient(){new Thread(new Runnable() {@Overridepublic void run() {try {HttpClient httpClient= new DefaultHttpClient();HttpGet httpGet = new HttpGet("http://www.baidu.com");HttpResponse httpResponse = httpClient.execute(httpGet);if(httpResponse.getStatusLine().getStatusCode() == 200){//请求和相应成功HttpEntity entity = httpResponse.getEntity();//防止中文乱码String responseText = EntityUtils.toString(entity,"utf-8");Message message = new Message();message.what = SHOW_RESPONSE_CONTENT;message.obj = responseText.toString();handler.sendMessage(message);}} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}).start();}
修改onClick方法,如下:
//重写点击方法@Overridepublic void onClick(View view) {if(view.getId() == R.id.send_request){//如果是点击发送按钮,则处理Http请求--使用HttpURLConnection//sendRequestWithHttpURLConnection();//如果是点击发送按钮,则处理Http请求--使用HttpClientsendRequestWithHttpClient();}}



效果如下:

更多相关文章

  1. Android(安卓)HttpClient网络通信
  2. Android开发实现计算器的例子
  3. android发送短信
  4. android inputmanager中事件的传递流程
  5. Android(安卓)Studio Toast/Notification中文乱码解决办法
  6. Android按钮美化
  7. Android---网络编程之Retrofit2整体结构了解以及+Okhttp3+rxjava
  8. Android---网络编程之OkHttp3整体结构了解以及使用
  9. Android应用程序请求SurfaceFlinger服务创建Surface的过程分析

随机推荐

  1. SoLoader,android动态加载so库
  2. Android(安卓)之怎么删除eclipse自动生成
  3. ListView中添加Button后,Button的点击事件
  4. Android Stduio 发生 Process 'command '
  5. Android 微信/支付宝 h5调原生支付
  6. android中的Bitmap
  7. 安卓开发
  8. ExpandableListView设置选中child的背景
  9. 怎么给Android(安卓)控件添加边框(样式)?
  10. Android命令行手动编译打包详解