Http协议网络请求java方式

来源:互联网 发布:thinkphp手机商城源码 编辑:程序博客网 时间:2024/06/05 19:38

HTTP(超文本传输协议)消息:客户端请求,服务器响应


主要请求方式:
GET:数据附在url后面,数据量小,安全性差。

POST:数据量大,支持各种数据类型,安全性高,服务器先接受数据长度再接收内容。


主要用到的以下类:

URL url = new URL("httpurl");//得到url实例,,URL是特殊的URI 统一资源定位符,URI 资源标识符

HttpConnection con = url.openConnectoin();//通过httpurl 得到HttpConnection 实例

con.setRequestMethod("");//设置请求状态,GET/POST/HEAD/PUT/DELETE/TRACE/CONNECT/OPTIONS

con.connect();//建立连接

con.getResponseCode;//返回得到响应状态,int值

通过con.get...可以得到输入输出流,能够像服务器传送数据并得到响应信息;

con.disconnect; 断开连接


使用:

网络请求是耗时操作,所以不能放在主线程中,可以使用handler或者异步任务

<span style="font-size:14px;">new AsyncTask<String, Void, String>() {@Overrideprotected String doInBackground(String... params) {return buildHttpConnect(params[0]);//封装的方法}/*得到响应数据的处理,赋给textView */@Overrideprotected void onPostExecute(String result) {mShowTxt.setText(result);};}.execute(httpUrl);</span>

通过传入目标url建立连接

private String buildHttpConnect(String url) {try {/* get请求传参方式url=url +"?user=admin&psw=123"  get处理中文乱码,可以调用URLEncoder.encode("params","UTF-8")*/URL httpUrl = new URL(url);HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();connection.setRequestMethod("POST");connection.setReadTimeout(10000);connection.setConnectTimeout(5000);connection.connect();/* post请求 传参方式)(post参数中文乱码,在服务器req.setContentType("text/html;charset=UTF-8");) */OutputStream os = connection.getOutputStream();PrintWriter writer = new PrintWriter(os);writer.print("user=admin&psw=123");writer.flush();/* 读取服务器响应内容 */InputStream is = connection.getInputStream();BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));StringBuilder builder = new StringBuilder();String str;while ((str = reader.readLine()) != null) {builder.append(str);}return builder.toString();} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally{//"关流",断开连接<span style="font-family: Arial, Helvetica, sans-serif;">}</span>
<span style="font-size:14px;">return null;}</span>

客户端中文乱码:

get请求中可以使用URLEncoder这个工具类,URLEncoder.encode("","UTF-8");

post请求中,可以在服务器那端设置 request.setContentType("text/html;charset=UTF-8");

响应乱码;

1.在new InputStreamReader(inputstream,"UTF-8")中可以指定他的编码

2.在服务端中设置 response.setCharset("UTF-8");

0 0