今天学到了HttpClient的使用,里面最关键的就是将表单和文件已Post方式提交到Java EE的项目中。
1) 再做项目HttpClientDemo前,先写工具类,为以后的项目开发提供方便。
package com.example.httpclientdemo.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) 开发界面main_activity.xml
<?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" />
<EditText
android:id="@+id/et_input_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/ples_input_name"
android:lines="1" >
</EditText>
<EditText
android:id="@+id/et_input_pwd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/ples_input_pwd"
android:inputType="textPassword"
android:lines="1" >
</EditText>
<EditText
android:id="@+id/et_input_filedir"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/ples_input_filedir"
android:lines="1" >
</EditText>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<Button
android:id="@+id/bt_post_form"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Post提交表单" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<Button
android:id="@+id/bt_post_file"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Post提交文件" />
</LinearLayout>
</LinearLayout>
3)配置strings.xml和配置config.xml文件内容
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">HttpClientDemo</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="app_title">使用HttpClient提交表单</string>
<string name="ples_input_name">请输入您的用户名</string>
<string name="ples_input_pwd">请输入您的密码</string>
<string name="ples_input_filedir">请输入文件路径</string>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="url_fromhttp_form">http://10.0.2.2:8080/WebSite/activity/clientPost</string>
<string name="url_fromhttp_file">http://10.0.2.2:8080/WebSite/upload/testsave</string>
</resources>
4)MainActivity中逻辑代码
package com.example.httpclientdemo;
import java.io.InputStream;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import com.example.httpclientdemo.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.Toast;
public class MainActivity extends Activity implements OnClickListener {
private EditText et_name;
private EditText et_pwd;
private EditText et_filedir;
private Button btn_post_form;
private Button btn_post_file;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_name = (EditText) findViewById(R.id.et_input_name);
et_pwd = (EditText) findViewById(R.id.et_input_pwd);
et_filedir = (EditText) findViewById(R.id.et_input_filedir);
btn_post_form = (Button) findViewById(R.id.bt_post_form);
btn_post_file = (Button) findViewById(R.id.bt_post_file);
btn_post_file.setOnClickListener(this);
btn_post_form.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
String name = et_name.getText().toString().trim();
String pwd = et_pwd.getText().toString().trim();
String path = getResources().getString(R.string.url_fromhttp_form);
String filepath = et_filedir.getText().toString().trim();
switch (v.getId()) {
case R.id.bt_post_form:
NameValuePair valuePair1 = new BasicNameValuePair("admin.name",
name);
NameValuePair valuePair2 = new BasicNameValuePair("admin.password",
pwd);
NameValuePair[] valuePairs = { valuePair1, valuePair2 };
try {
HttpResponse response = NetUtil.clientPost(path, valuePairs);
InputStream is = response.getEntity().getContent();
Toast.makeText(this, NetUtil.getStringbyInputStream(is),
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// TODO Auto-generated catch block
Toast.makeText(this, "网络出错。。。", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
break;
case R.id.bt_post_file:
try {
Toast.makeText(
this,
NetUtil.clientPostFile(
getResources().getString(
R.string.url_fromhttp_file), filepath),
1).show();
} catch (NotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
default:
break;
}
}
}
总结:
安卓开发的核心就是通过接口与远程Web服务的交互,这是安卓应用开发的关键所在。
安卓可以使用HttpClient对象以Get/Post的方式提交数据,并得到响应数据。常用的提交方式为Post提交。而服务器返回常用的则是Json格式。