网络编程(下)

1.HttpURLConnection 提交数据

  • GET提交
Get请求
代码如下:

public void submit(String path,String userName,String passWord)throw Exception{
    //get提交的路径
    String finalPath =path+"?qq="+URLEncoder.encode(userName, "utf-8")
    +"&pwd="+URLEncoder.encode(passWord, "utf-8");

    URL url = new URL(finalPath);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    //设置请求方式及访问过期时间
    conn.setRequestMethod("GET");
    conn.setConnectTimeout(5000);
    //得到状态码
    int code = conn.getResponseCode();

    if(code == 200){
        InputStream is = conn.getInputStream();
        String result = StreamTools.readStream(is);
        return result;
    }else{
        return null;
    }
}
  • Post提交
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//1.设置请求方式为POST
conn.setRequestMethod("POST"); //注意单词必须大写.
conn.setConnectTimeout(5000);
//2.设置http请求数据的类型为表单类型
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//3.设置给服务器写的数据的长度
//qq=10000&pwd=abcde
String data = "qq="+URLEncoder.encode(qq, "utf-8")+"&pwd="+URLEncoder.encode(pwd, "utf-8");
conn.setRequestProperty("Content-Length", String.valueOf(data.length()));
//4.记得指定要给服务器写数据
conn.setDoOutput(true);
//5.开始向服务器写数据
conn.getOutputStream().write(data.getBytes());
int code = conn.getResponseCode();

2.get和post差异

  • 在http 协议中,get请求协议没有请求体,只有请求头和请求行,因此如果想使用get 方式提交数据,只能通过在url 后面加上要提交的参数。这也意味着get 方式只能提交比较小的参数。
    如果get 方式提交的参数有特殊字符或者中文字符那么必须对其进行URL 编码,不然会导致服务器接收到的数据乱码。
  • 对于post 请求,提交的数据位于请求体中,因此需要设置connection.setDoOutput(true);参数,该参数设置后才允许将提交的数据通过输出流的形式提交。不过需要说明的是虽然采用post 方式提交,依然需要将参数进行URL 编码。

3.HttpClient 提交数据

HttpClient 是Apache Jakarta Common 下的子项目,提供了高效的、最新的、功能丰富的支持HTTP 协议的客户端编程工具包,并且它支持HTTP 协议最新的版本。

  • Get方式提交
String path = "http://192.168.1.103:8080/web/LoginServlet?qq="
                +URLEncoder.encode(qq, "utf-8")+"&pwd="
                +URLEncoder.encode(pwd, "utf-8");
//1.打开浏览器
HttpClient client = new DefaultHttpClient();
//2.输入地址或者数据
HttpGet httpGet = new HttpGet(path);
//3.敲回车
HttpResponse response = client.execute(httpGet);
//获取状态码
int code = response.getStatusLine().getStatusCode();
  • Post方式提交
String path = "http://192.168.1.103:8080/web/LoginServlet";
//1.打开浏览器
HttpClient client = new DefaultHttpClient();
//2.输入地址或者数据
HttpPost httpPost = new HttpPost(path);
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("qq", qq));
parameters.add(new BasicNameValuePair("pwd", pwd));
httpPost.setEntity(new UrlEncodedFormEntity(parameters, "utf-8"));
//3.敲回车
HttpResponse response = client.execute(httpPost);
//获取状态码
int code = response.getStatusLine().getStatusCode();

4.AsyncHttpClient提交数据

  • Get方式提交
//请求路径
String path = "http://192.168.1.103:8080/web/LoginServlet?qq="
            +URLEncoder.encode(qq)+"&pwd="+URLEncoder.encode(pwd);
AsyncHttpClient client = new AsyncHttpClient();

client.get(path, new AsyncHttpResponseHandler() {
    @Override
    public void onSuccess(int statusCode, Header[] headers,byte[] responseBody) {
        //请求成功
        tv_status.setText(new String(responseBody));
    }
    @Override
    public void onFailure(int statusCode, Header[] headers,byte[] responseBody, Throwable error) {
        //请求失败
        tv_status.setText("http请求失败"+new String(responseBody));
    }
});
  • Post方式提交
String path = "http://192.168.1.103:8080/web/LoginServlet";
AsyncHttpClient client = new AsyncHttpClient();

RequestParams params = new RequestParams();
params.put("qq", qq);
params.put("pwd", pwd);

client.post(path, params, new AsyncHttpResponseHandler(){
    @Override
    public void onSuccess(int statusCode, Header[] headers,byte[] responseBody) {
        tv_status.setText("登陆结果:"+new String(responseBody));
    }
    @Override
    public void onFailure(int statusCode, Header[] headers,byte[] responseBody, Throwable error) {
        tv_status.setText("请求失败请检查网络");
    }
});
  • 文件上传:在文本框中输入文件路径,点击上传按钮,进行上传到服务器
public void upload(View view){
    String path = et_path.getText().toString().trim();
    File file = new File(path);
    if(file.exists()&&file.length()>0){
        //上传
        AsyncHttpClient client = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        try {
            params.put("file", file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        client.post("http://192.168.1.103:8080/web/UploadServlet", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                Toast.makeText(MainActivity.this, "上传成功", 0).show();
            }
            @Override
            public void onFailure(int statusCode, Header[] headers,byte[] responseBody, Throwable error) {
                Toast.makeText(MainActivity.this, "上传失败", 0).show();
            }
        });
    }else{
        Toast.makeText(this, "请检查文件是否存在", 0).show();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值