输入一个手机号得到归属地——httpClient应用
2014-06-10 22:09
211 查看
这个Demo是学习Android第四天的最后一个项目Demo,主要是通过向远程Web项目发送数据(手机号),并得到相应(手机号对应归属地)
1)在编写Demo之前先编写工具类
2)配置strings.xml和配置config.xml
3)开发界面
4)MainAcrivity相关的业务逻辑
总结:
这个Demo是对HttpClient学习的应用,输入一个手机号并将其发送到http://tcc.taobao.com/cc/json/mobile_tel_segment.htm,然后得到相应数据并显示到TextView和Toast中。
1)在编写Demo之前先编写工具类
package com.example.webservice4json.util; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.multipart.FilePart; import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; import org.apache.commons.httpclient.methods.multipart.Part; import org.apache.commons.httpclient.methods.multipart.StringPart; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Environment; public class NetUtil { /** * 该方法可以根据一个url返回一个图片 * * @param address * 得到图片的统一资源定位器地址 * @param flag * 是否写入缓存 * @return 图片 * @throws Exception */ public static Bitmap getImg(String address, boolean flag) throws Exception { // 声明 URL URL url = new URL(address); // 得到打开的链接 URLConnection conn = url.openConnection(); conn.setRequestProperty("method", "get"); conn.setReadTimeout(5000); InputStream is = conn.getInputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] bytes = new byte[1024]; int len = 0; while ((len = is.read(bytes)) != -1) { bos.write(bytes, 0, len); } byte[] imgBytes = bos.toByteArray(); OutputStream fos = null; if (flag) { // 1.根据请求地址得到图片文件名 int start = address.lastIndexOf("/"); String iconName = address.substring(start + 1); File iconfile = new File(Environment.getExternalStorageDirectory(), iconName); fos = new FileOutputStream(iconfile); fos.write(imgBytes); fos.flush(); fos.close(); } return BitmapFactory.decodeByteArray(imgBytes, 0, imgBytes.length); } public static String getHtml(String address) throws Exception { // 声明 URL URL url = new URL(address); // 得到打开的链接 URLConnection conn = url.openConnection(); conn.setRequestProperty("method", "get"); conn.setReadTimeout(5000); InputStream is = conn.getInputStream(); // 得到网页编码类型 String contentType = conn.getContentType(); // 截取等号 = 得到结果如:utf-8、GBK String type = contentType.split("=")[1]; ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] bytes = new byte[1024]; int len = 0; while ((len = is.read(bytes)) != -1) { bos.write(bytes, 0, len); } byte[] imgBytes = bos.toByteArray(); return new String(imgBytes, type); } public static String getJson(String address) throws Exception { // 声明 URL URL url = new URL(address); // 得到打开的链接 URLConnection conn = url.openConnection(); conn.setRequestProperty("method", "get"); conn.setReadTimeout(5000); InputStream is = conn.getInputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] bytes = new byte[1024]; int len = 0; while ((len = is.read(bytes)) != -1) { bos.write(bytes, 0, len); } byte[] imgBytes = bos.toByteArray(); return new String(imgBytes); } public static HttpResponse clientPost(String path, NameValuePair... nameValuePairs) throws Exception { // 得到模拟http客户端 HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(path); List<NameValuePair> parameters = Arrays.asList(nameValuePairs); HttpEntity entity = new UrlEncodedFormEntity(parameters, "utf-8"); post.setEntity(entity); HttpResponse response = client.execute(post); return response; } public static String clientPostFile(String path, String filepath) throws Exception { // 得到模拟http客户端 File file = new File(filepath); org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient(); Part[] parts = { new StringPart("name", "小王子"), new StringPart("password", "xiaowangzi"), new FilePart("file", file) }; PostMethod postMethod = new PostMethod(path); postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams())); httpClient.getHttpConnectionManager().getParams() .setConnectionTimeout(5000); int status = httpClient.executeMethod(postMethod); if (status == 200) { return new String(postMethod.getResponseBody()); } else { throw new IllegalArgumentException("文件不存在,或者文件不存在。。。"); } } public static String getStringbyInputStream(InputStream is, String charset) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); int len = 0; byte[] bytes = new byte[1024]; while ((len = is.read(bytes)) != -1) { bos.write(bytes, 0, len); } return new String(bos.toByteArray(), charset); } public static String getStringbyInputStream(InputStream is) throws IOException { return getStringbyInputStream(is, "utf-8"); } }
2)配置strings.xml和配置config.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">WebService4Json</string> <string name="action_settings">Settings</string> <string name="app_title">手机号归属地查询系统</string> <string name="et_input_phoneno_hint">请输入您要查询的手机号</string> </resources>
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="url">http://tcc.taobao.com/cc/json/mobile_tel_segment.htm</string> </resources>
3)开发界面
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/app_title" android:textColor="@android:color/darker_gray" android:textSize="20sp" /> <EditText android:id="@+id/et_input_phoneno" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="@string/et_input_phoneno_hint" android:inputType="phone" android:textColor="@android:color/darker_gray" android:textSize="20sp" /> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_horizontal|center_vertical" > <Button android:id="@+id/bt_post" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="查询号码归属地" /> </LinearLayout> <ScrollView android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/tv_result" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="查询结果在这里显示" /> </ScrollView> </LinearLayout>
4)MainAcrivity相关的业务逻辑
package com.example.webservice4json; import java.io.InputStream; import org.apache.http.message.BasicNameValuePair; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import com.example.webservice4json.util.NetUtil; import android.os.Bundle; import android.app.Activity; import android.content.res.Resources.NotFoundException; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity implements OnClickListener { private EditText et_input_phoneno; private Button btn_post; private TextView tv_reslut; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et_input_phoneno = (EditText) findViewById(R.id.et_input_phoneno); btn_post = (Button) findViewById(R.id.bt_post); tv_reslut = (TextView) findViewById(R.id.tv_result); // 注册单击事件 btn_post.setOnClickListener(this); } @Override public 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; } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.bt_post: String phoneno = et_input_phoneno.getText().toString().trim(); Toast.makeText(this, "手机号码:" + phoneno, 1).show(); NameValuePair nameValuePair = new BasicNameValuePair("tel", phoneno); NameValuePair[] nameValuePairs = { nameValuePair }; HttpResponse httpResponse; try { httpResponse = NetUtil.clientPost( getResources().getString(R.string.url), nameValuePairs); InputStream is = httpResponse.getEntity().getContent(); String result = NetUtil.getStringbyInputStream(is, "GBK"); Toast.makeText(this, result, 1).show(); tv_reslut.setText(result + "\n" + result); } catch (NotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } break; default: break; } } }
总结:
这个Demo是对HttpClient学习的应用,输入一个手机号并将其发送到http://tcc.taobao.com/cc/json/mobile_tel_segment.htm,然后得到相应数据并显示到TextView和Toast中。
相关文章推荐
- 1. 请用C#的面向对象语言 实现 一个计算器控制台程序,要求输入两个数和运算符号,得到结果
- VC得到当前目录与得到应用程序目录的一个应用
- 输入一个字符,判断它是否为大写字母,如果是,将它转换成小写字母;如果不是,不转换。然后输出最后得到的字符.cpp
- 输入一个字符串表达式,输出计算结果(队列、栈的应用)
- 人民币金额大写 在与财务相关的应用中,经常会用到人民币金额的大写,比如发票的打印程序。 本题的任务是:从键盘输入一个十亿以内的正整数(int类型),把它转换为人民币金额大写(不考虑用户输入错误
- 测测两人的关系.一个小程序,根据用户输入的名字得到笔画数!
- 作业三-应用分支与循环结构解决问题——.输入一个整数 x,计算并输出下列分段函数 sign(x) 的值
- C#--第三周实验--任务2--输入一个由若干字符组成的字符串,输出其中的大写字母、小写字母、数字和其他字符的个数(控制台应用)
- 2. 编写一个Java应用程序,用户从键盘输入一个1~9999之间的数,程序将判断这个数是几位数,并判断这个数是否是回文数。回文数是指将该数含有的数字逆序排列后得到的数和原数相同,例如12121、32
- 1.编写一个简单的C语言程序:根据输入的两个整数求平均值并且在终端输出,通过gcc编译器得到它的汇编程序文件。 2.编写一个C语言程序:打印输出所有“水仙花数”,用gdb调试程序(给出步骤)。所谓“
- VC得到当前目录与得到应用程序目录的一个应用
- 一个很好的国家autocomplete插件,输入国家code,就能得到国家名字,甚至能得到国家的currency(这个是我一个个手动录进去)
- 九宫格扩展,输入一个奇数,得到横竖斜相加相等结果
- 给你一个单词a,如果通过交换单词中字母的顺序可以得到另外的单词b,那么定义b是a的兄弟单词。现在给你一个字典,用户输入一个单词,让你根据字典找出这个单词有多少个兄弟单词。
- C#--第2周实验--任务8--编写一个控制台应用--输入10个数存入数组,求最大值、最小值和平均值
- 输入一个表得到这个表的查询结果
- 递归的应用——输入一个整型值(无符号),把它转换成字符并打印它,前导0被删除
- C#--第2周实验--创建一个控制台应用--输入并输出一行字符串
- 安卓完成一个应用,用户可以根据自己输入的地址下载网络上的图片和网页信息
- 1.编写一个简单的C语言程序:根据输入的两个整数求平均值并且在终端输出,通过gcc编译器得到它的汇编程序文件。 2.编写一个C语言程序:打印输出所有“水仙花数”,用gdb调试程序(给出步骤)。所谓“