在EditText中输入手机号,发送到服务器,服务器返回一个数据
m_shujuhao是一个EditText
/**
* 提交电话号
*/
public void login_btn_huoquyanzhengma_onclick(View v) {
// 向服务器提交的数据
String shoujihaoDataStr = null;
// 把输入框的数据,封装成向服务器提交的数据
if (null != m_shujuhao.getText().toString().trim()
&& m_shujuhao.getText().toString().trim().length() > 0) {
String shoujihaoStr = m_shujuhao.getText().toString().trim();
Map<String, String> map = new HashMap<String, String>();
map.put("phone", shoujihaoStr);
// post请求要发送的数据,phone=15388639869;
StringBuffer stringBuffer = new StringBuffer();
if (map != null && map.size() > 0) {
for (Map.Entry<String, String> entry : map.entrySet()) {
stringBuffer.append(entry.getKey()).append("=");
stringBuffer.append(entry.getValue());
stringBuffer.append("&");
}
shoujihaoDataStr = stringBuffer.deleteCharAt(
stringBuffer.length() - 1).toString();
Log.i("1", "往流里写的手机号>>>" + shoujihaoDataStr);
}
// 启动异步任务类请求网络
new MyRequestAsyncTaskPost(MyUrl.domainName
+ MyUrl.callOnurldianhuahao, shoujihaoDataStr,
Login_Activity.this).execute();
// 拿到静态变量的数据,也就是从服务器上返回的数据
// 启动异步任务类,也是开启子线程,线程是同时进行的,所以在这停一下,让子线程先运行
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
m_serverData_shuojihao = MyParameter.myDataString;
Log.i("1", "从服务器上返回,用静态变量传过来的数据..." + m_serverData_shuojihao);
// 解析
if (m_serverData_shuojihao != null
&& m_serverData_shuojihao.length() > 0) {
LoginBack phoneBack = DataParse.method2(m_serverData_shuojihao);
// 把解析后的数据信息吐丝一下
Toast.makeText(this, phoneBack.getMessage(), 10).show();
}
}
}
异步任务类
package com.boyouhui.www.http;
import java.util.List;
import com.boyouhui.www.MainActivity;
import com.boyouhui.www.domain.Person;
import com.boyouhui.www.http.MyResponse.ResponFailed;
import com.boyouhui.www.http.MyResponse.ResponSesuccess;
import com.boyouhui.www.util.DataParse;
import com.boyouhui.www.util.MyParameter;
import com.boyouhui.www.util.MyUrl;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
/**
* 异步任务类开启子线程
*
*/
public class MyRequestAsyncTaskPost extends AsyncTask<String, String, String> {
String path;
Context context;
String mydataStr;
public MyRequestAsyncTaskPost(String path,String mydataStr, Context context) {
this.path=path;
this.context = context;
this.mydataStr=mydataStr;
Log.i("1", "异步任务类被启动了。。。");
}
// 本方法是子线程,在里面仅限耗时操作
// 本方法中的参数 String... params,相当于String[] paparams;
// 可以通过 new MyRequestAsyncTask().execute("路径");启动
// 通过params[0];就可以拿到传入的路径
@Override
protected String doInBackground(String... params) {
// 调用路径
String paramsStr = path;
// 调用请求
String dataStr = HttpRequest.methodPost(path, mydataStr);
return dataStr;
}
// 把从服务器上的数据传到主线程中
@Override
protected void onPostExecute(String dataStr) {
super.onPostExecute(dataStr);
//把服务器上拿到的数据传给---myApplication-----传给所需要的类
//用静态变量把数据传出去
//MyParameter.myDataString=dataStr;
MyResponse myResponse = new MyResponse();
// 如果数据不为空,则请求成功
if (dataStr != null) {
// 接口传参,接收到接口传过来的数据
myResponse.onSuccess(new ResponSesuccess() {
@Override
public void setResult(String s) {
//Toast.makeText(context, s, 10).show();
Log.i("1", "网络状态。。。" + s);
}
});
}
// 如果数据为空,则请求失败
else if (dataStr == null) {
myResponse.onFailed(new ResponFailed() {
@Override
public void setResult(String s) {
//Toast.makeText(context, s, 10).show();
Log.i("1", "网络状态。。。" + s);
}
});
}
}
}
真正发送请求的代码
package com.boyouhui.www.http;
/**
* 本类发http请求,记着要开网络权限
*
*/
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.json.JSONObject;
import com.boyouhui.www.util.MyParameter;
import android.hardware.Camera.Parameters;
import android.util.Log;
public class HttpRequest {
// 两个参数1路径2往流里写的数据
public static String methodPost(String path, String dataStr) {
String bStr = null;
DataOutputStream dataOutputStream = null;
ByteArrayOutputStream outputStream = null;
InputStream inputStream = null;
try {
// //生成一个json数据,准备传到服务器
// JSONObject jsonObject = new JSONObject();
// jsonObject.put("name", "张三");
// jsonObject.put("age", "20");
// //拼接起来的,带有json数据的路径
// String jsonStr = "param=" + jsonObject.toString();
/**
* 把路径原始路径写到URL中
*/
URL url = new URL(path);
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
httpURLConnection.setConnectTimeout(3000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
// 数据的类型
httpURLConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
// 向服务器传数据的长度
httpURLConnection.setRequestProperty("Content-Length",
String.valueOf(dataStr.length()));
// 得到输出流并封装
dataOutputStream = new DataOutputStream(
httpURLConnection.getOutputStream());
/**
* 把要传的参数写到流中
*
*/
//dataOutputStream.writeBytes(dataStr);
dataOutputStream.write(dataStr.getBytes());
if (httpURLConnection.getResponseCode() == 200) {
Log.i("1", "进到200连接成功。。。");
inputStream = httpURLConnection.getInputStream();
outputStream = new ByteArrayOutputStream();
byte[] bs = new byte[10];
int len = 0;
while ((len = inputStream.read(bs)) != -1) {
outputStream.write(bs, 0, len);
}
// 把数据转化成字节字节数组
byte[] b = outputStream.toByteArray();
// 把数据转化成字符串
bStr = new String(b, "UTF-8");
// 打印一下拿到的数据
Log.i("1", "从服务器上拿到的数据,从流装-->字节数组-->字符串" + bStr);
//用静态变量把数据传出去
MyParameter.myDataString=bStr;
}
} catch (Exception e) {
e.printStackTrace();
// 如果请求发送失败,则返回的字符串bStr=null;
// 只要在发请求的activity中判断bStr=null,则发送请求失败
return bStr;
}
finally {
// // 关流有可能出错
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return bStr;
}
public static String methodGet2(String path) {
String dataStr = null;
InputStream is = null;
ByteArrayOutputStream os = null;
try {
URL url = new URL(path);
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.setRequestMethod("GET");
if (httpURLConnection.getResponseCode() == 200) {
Log.i("1", "网络连接成功。。。");
is = httpURLConnection.getInputStream();
os = new ByteArrayOutputStream();
byte[] b = new byte[10];
int len = 0;
if ((is.read(b)) != -1) {
os.write(b, 0, len);
}
byte[] myarray = os.toByteArray();
dataStr = new String(myarray, "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return dataStr;
};
}