您的位置:首页 > 理论基础 > 计算机网络

输入一个手机号得到归属地——httpClient应用

2014-06-10 22:09 211 查看
这个Demo是学习Android第四天的最后一个项目Demo,主要是通过向远程Web项目发送数据(手机号),并得到相应(手机号对应归属地)

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中。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐