在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、结果

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

Android中使用HttpURLConnection和HttpClient发送Http请求_第1张图片

这就是服务器返回给我吗的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();}}



效果如下:

Android中使用HttpURLConnection和HttpClient发送Http请求_第2张图片

更多相关文章

  1. Android抽屉式按钮实现
  2. android设置textview限制字数以省略号显示的方法
  3. Android子控件超出父控件方法
  4. Android Studio下载及离线升级方法
  5. Delphi XE5 Android 运行黑屏卡死的解决方法
  6. Android编程: 调试方法

随机推荐

  1. Go语言学习5-切片类型
  2. 关于OpenGL游戏全屏模式的设置
  3. VsCode常用设置,新手必备!
  4. 教你用Python爬虫自制有道翻译词典
  5. Go语言学习4-数组类型
  6. 《游戏程序设计模式》 2.2 - 游戏循环
  7. 网页游戏用的什么编程语言
  8. MySql基础语法的学习-基础的查询语句
  9. SpringBoot+Vue3前后端分离,实战wiki知识
  10. 态路小课堂丨QSFP-DD封装模式光模块接口