概述
我们在开发的使用,直接使用的开源框架,例如:Xutil,Volley开源框架直接访问网络,但是我们也需要知道其中的一些知识,了解一下怎样访问网络的。下面我们模拟以下客户端和服务端,看看POST。
首先看POST线程类的定义
//获取登录历史记录
class WxpDataPostThread extends Thread {
private String UserName;
private String UserPos;
private TextView show_content;
private String url = "";
private Handler handler = new Handler();
public WxpDataPostThread(String url, String UserName, String UserPos, TextView show_content) {
this.UserName = UserName;
this.UserPos =UserPos;
this.show_content = show_content;
this.url = url;
}
@Override
public void run() {
super.run();
getRun();
}
private void getRun() {
if (TextUtils.isEmpty(url)) {
throw new NullPointerException("please ensure url is not equals null ");
}
BufferedReader bufferedReader = null;
try {
URL httpUrl = new URL(url);
HttpURLConnection httpURLConnection = (HttpURLConnection) httpUrl.openConnection();
//设置请求头header
httpURLConnection.setRequestProperty("test-header", "post-header-value");
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setReadTimeout(5000);
//设置请求参数
if (!TextUtils.isEmpty(UserName) && !TextUtils.isEmpty(UserPos)) {
OutputStream outputStream = httpURLConnection.getOutputStream();
String params = "UserName=" + UserName + "&UserPos=" + UserPos;
outputStream.write(params.getBytes());
show_content.setText(params);
}
//获取内容
InputStream inputStream = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
final StringBuffer stringBuffer = new StringBuffer();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
}
handler.post(new Runnable() {
@Override
public void run() {
//解析json
String msg = "";
try {
JSONObject jsonObject = new JSONObject(stringBuffer.toString());
String jkey = "";
String jVal = "";
int iCount = jsonObject.length();
for (int i = iCount; i >= 1; i--) {
jkey = String.valueOf(i);
jVal = jsonObject.getString(jkey);
msg = msg + jkey + " " + jVal + "rnrn";
}
} catch (JSONException e) {
e.printStackTrace();
}
//
show_content.setText(msg);
}
});
} catch (Exception e) {
show_content.setText(e.toString());
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
show_content.setText(e.toString());
}
}
}
}
}
2 其次看看ACTIVITY中的调用
public class MainActivity extends AppCompatActivity {
private Button btnSubmit;
private EditText edtUser;
private EditText edtPass;
private EditText edtReturn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取控件
btnSubmit = (Button) findViewById(R.id.btSubmit);
edtUser = (EditText) findViewById(R.id.editName);
edtPass = (EditText) findViewById(R.id.editPWD);
edtReturn = (EditText) findViewById(R.id.editReturn);
//设置事件
btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// edtPos.setText("四川省成都市郫都区学府街");
String UserName = edtUser.getText().toString().trim();
String PassWord = edtPass.getText().toString().trim();
String UserPos=edtPos.getText().toString().trim();
if (UserName.length() < 5) {
Toast.makeText(MainActivity.this, "用户名不能少于5个字符", Toast.LENGTH_LONG).show();
edtReturn.setText("用户名不能少于5个字符");
return;
}
if (PassWord.length() < 5) {
Toast.makeText(MainActivity.this, "密码字符不能少于5个", Toast.LENGTH_LONG).show();
edtReturn.setText("密码不能少于5个字符");
return;
}
if (UserPos.indexOf("市")<=0) {
Toast.makeText(MainActivity.this, "定位信息不准确", Toast.LENGTH_LONG).show();
edtReturn.setText("定位信息不准确,请再次点击‘位置’按钮获取定位信息");
return;
}
String url = "http://x.x.x.x/Default3.aspx?";
new WxpDataPostThread(url, UserName, UserPos, edtReturn).start();
edtReturn.setText("开始登陆");
}
});
}
//end of class
}
对于POST请求,
String url = "http://x.x.x.x/Default3.aspx?"; //服务器处理页面
String params="UserName="+ name+"&age="+ age; //参数设计
outputStream.write(params.getBytes()); //
httpURLConnection.setReadTimeout(5000); //设置超时时间
httpURLConnection.setRequestMethod("POST"); //设置请求方法
POST请求的OutputStream实际上不是网络流,而是写入内存,在getInputStream中才真正把写到流里面的内容作为正文与根据之前的配置生成的http request头合并成真正的http request,并在此时才真正向服务器发送。
获取从服务器传回来的内容
InputStream inputStream = httpURLConnection.getInputStream();
将InputStream 转换成BufferedReader,便于操作流
将流中的数据存入到了StringBuffer中,最后设置给展示内容的TextView上。
最后要记得关闭流。
//
//获取内容
InputStream inputStream = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
final StringBuffer stringBuffer = new StringBuffer();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
}
//解析JSON
//解析json
String msg="";
try {
JSONObject jsonObject = new JSONObject(stringBuffer.toString());
String jkey="";
String jVal="";
for(int i=1;i<=jsonObject.length();i++) {
jkey=String.valueOf(i);
jVal = jsonObject.getString(jkey);
msg = msg + jkey+" "+ jVal + "rn";
}
} catch (JSONException e) {
e.printStackTrace();
}
//
show_content.setText(msg);
3 对于服务器端的响应文件Default3.aspx的主要代码为
这里只响应了一个参数UserName,然后根据用户名写入登录记录
后继利用using Newtonsoft.Json;构造JSON
利用 Dictionary构造字典,最后JsonConvert.SerializeObject(dic);序列化成字符串进行发送。
Dictionary<string, string> dic = new Dictionary<string, string>();
if (System.IO.File.Exists(userFile))
{
string[] readText = System.IO.File.ReadAllLines(userFile);
int icount = readText.Count();
for (int i = icount - 1; i >= 0; i--)
dic.Add(Convert.ToString(i), readText[i]);
}
string jsonString= JsonConvert.SerializeObject(dic);
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(jsonString);
Response.End();
pprotected void Page_Load(object sender, EventArgs e)
{
string UserName = Request["UserName"];
string UserPos = Request["UserPos"];
if (UserName.Length <= 0)
{
//输出记录
Response.Write("<p>登录记录</p>");
return;
}
string userFile = "D:\phpstudy_pro\WWW\WebSite2\UserName\" + UserName + ".txt";
if (System.IO.File.Exists(userFile))
{
//写入文件
System.IO.StreamWriter strWriter;
strWriter = System.IO.File.AppendText(userFile);
strWriter.WriteLine(UserName + " " + UserPos + " " + DateTime.Now.ToString());
strWriter.Close();
}
else
{
//写入文件
System.IO.StreamWriter strWriter;
strWriter = System.IO.File.CreateText(userFile);
strWriter.WriteLine(UserName + " " + UserPos + " " + DateTime.Now.ToString());
strWriter.Close();
}
//输出登录记录
Dictionary<string, string> dic = new Dictionary<string, string>();
if (System.IO.File.Exists(userFile))
{
string[] readText = System.IO.File.ReadAllLines(userFile);
int icount = readText.Count();
for (int i = icount - 1; i >= 0; i--)
dic.Add(Convert.ToString(i), readText[i]);
}
//string json = "[{"name":"Pratik"},{"name": "Parth"}]";
string jsonString= JsonConvert.SerializeObject(dic);
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(jsonString);
Response.End();
}
最后
以上就是辛勤小甜瓜为你收集整理的使用HttpURLConnection发送post请求的全部内容,希望文章能够帮你解决使用HttpURLConnection发送post请求所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复