Sample Code for sending requests and receiving responses in Android HTTP

Source: Internet
Author: User

Add permission
First, add the network access permission to manifest: Copy codeThe Code is as follows: <manifest...>
<Uses-permission android: name = "android. permission. INTERNET"/>
...
</Manifest>

The complete Manifest file is as follows: Copy codeThe Code is as follows: <? Xml version = "1.0" encoding = "UTF-8"?>
<Manifest xmlns: android = "http://schemas.android.com/apk/res/android"
Package = "com. example. httpdemo1"
Android: versionCode = "1"
Android: versionName = "1.0" type = "codeph" text = "/codeph">
<Uses-sdk
Android: minSdkVersion = "8"
Android: targetSdkVersion = "17"/>
<Uses-permission android: name = "android. permission. INTERNET"/>
<Application
Android: allowBackup = "true"
Android: icon = "@ drawable/ic_launcher"
Android: label = "@ string/app_name"
Android: theme = "@ style/AppTheme">
<Activity
Android: name = "com. example. httpdemo1.HttpDemo1Activity"
Android: label = "@ string/app_name">
<Intent-filter>
<Action android: name = "android. intent. action. MAIN"/>
<Category android: name = "android. intent. category. LAUNCHER"/>
</Intent-filter>
</Activity>
</Application>
</Manifest>

The layout code is as follows: Copy codeThe Code is as follows: <RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android"
Xmlns: tools = "http://schemas.android.com/tools"
Android: layout_width = "match_parent"
Android: layout_height = "match_parent"
Android: paddingBottom = "@ dimen/activity_vertical_margin"
Android: paddingLeft = "@ dimen/activity_horizontal_margin"
Android: paddingRight = "@ dimen/activity_horizontal_margin"
Android: paddingTop = "@ dimen/activity_vertical_margin"
Tools: context = ". HttpDemo1Activity">
<TextView
Android: id = "@ + id/myWebTitle"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: text = ""/>
<Button
Android: id = "@ + id/requestBtn"
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
Android: layout_alignParentBottom = "true"
Android: text = "Send Request"/>
<WebView
Android: id = "@ + id/webview"
Android: layout_width = "fill_parent"
Android: layout_height = "match_parent"
Android: layout_above = "@ id/requestBtn"
Android: layout_below = "@ id/myWebTitle"/>
</RelativeLayout>
Activity_http_demo1.xml

Main Code:Copy codeThe Code is as follows: package com. example. httpdemo1;
Import java. io. BufferedReader;
Import java. io. IOException;
Import java. io. InputStream;
Import java. io. InputStreamReader;
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 android. OS. Bundle;
Import android. app. Activity;
Import android. view. View;
Import android. view. View. OnClickListener;
Import android. webkit. WebView;
Import android. widget. Button;
Public class HttpDemo1Activity extends Activity
{
Private Button mSendReqBtn = null; // send the request Button
Private WebView mWebView = null; // used to display the result. The response result is displayed by loading the html string instead of loading the URL in WebView.
// Response
Private HttpResponse mHttpResponse = null;
// Entity
Private HttpEntity mHttpEntity = null;
@ Override
Protected void onCreate (Bundle savedInstanceState)
{
Super. onCreate (savedInstanceState );
SetContentView (R. layout. activity_http_demo1 );
MSendReqBtn = (Button) findViewById (R. id. requestBtn );
MSendReqBtn. setOnClickListener (mSendClickListener );
MWebView = (WebView) findViewById (R. id. webview );
}
Private OnClickListener mSendClickListener = new OnClickListener ()
{
@ Override
Public void onClick (View v)
{
// Generate a request object
HttpGet httpGet = new HttpGet ("http://www.baidu.com /");
// Generate an Http client object
HttpClient httpClient = new DefaultHttpClient ();
// Use the Http client to send the request and obtain the response content.
InputStream inputStream = null;
Try
{
// Send the request and obtain the response object
MHttpResponse = httpClient.exe cute (httpGet );
// Obtain the Response Message entity
MHttpEntity = mHttpResponse. getEntity ();
// Obtain an input stream
InputStream = mHttpEntity. getContent ();
BufferedReader bufferedReader = new BufferedReader (
New InputStreamReader (inputStream ));
String result = "";
String line = "";
While (null! = (Line = bufferedReader. readLine ()))
{
Result + = line;
}
// Print the result. You can view it in LogCat.
System. out. println (result );
// Load the content to WebView display
MWebView. getSettings (). setDefaultTextEncodingName ("UTF-8 ");
// Directly use mWebView. loadData (result, "text/html", "UTF-8"); the webpage cannot be found
// The following method can be used for normal display (but it is relatively wide. You can drag it to see the Baidu logo)
MWebView. loadDataWithBaseURL (null, result, "text/html ",
"UTF-8", null );
// Directly load the URL to display the page (but this example is mainly used to verify whether the returned string is correct, so the following line of code is not required)
// MWebView. loadUrl ("http://www.baidu.com /");
}
Catch (Exception e)
{
E. printStackTrace ();
}
Finally
{
Try
{
InputStream. close ();
}
Catch (IOException e)
{
E. printStackTrace ();
}
}
}
};
}

The program running result is as follows:

References
Android development video tutorial HTTP operations. Http://www.marsdroid.org
Android Reference: package org. apache. http:
Http://developer.android.com/reference/org/apache/http/package-summary.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.