java-http通信

java项目使用HTTP的请求。主要有两种方式:
使用JDK自带的java.net包下的HttpURLConnection方式。

使用apache的HttpClient方式。

一、使用JDK自带的java.net包下的HttpURLConnection方式。

方法摘要
abstract  void disconnect()
          指示近期服务器不太可能有其他请求。
 InputStream getErrorStream()
          如果连接失败但服务器仍然发送了有用数据,则返回错误流。
static boolean getFollowRedirects()
          返回指示是否应该自动执行 HTTP 重定向 (3xx) 的 boolean 值。
 String getHeaderField(int n)
          返回 nth 头字段的值。
 long getHeaderFieldDate(String name, long Default)
          返回解析为日期的指定字段的值。
 String getHeaderFieldKey(int n)
          返回 nth 头字段的键。
 boolean getInstanceFollowRedirects()
          返回此 HttpURLConnectioninstanceFollowRedirects 字段的值。
 Permission getPermission()
          返回一个权限对象,其代表建立此对象表示的连接所需的权限。
 String getRequestMethod()
          获取请求方法。
 int getResponseCode()
          从 HTTP 响应消息获取状态码。
 String getResponseMessage()
          获取与来自服务器的响应代码一起返回的 HTTP 响应消息(如果有)。
 void setChunkedStreamingMode(int chunklen)
          此方法用于在预先知道内容长度时启用没有进行内部缓冲的 HTTP 请求正文的流。
 void setFixedLengthStreamingMode(int contentLength)
          此方法用于在预先已知内容长度时启用没有进行内部缓冲的 HTTP 请求正文的流。
static void setFollowRedirects(boolean set)
          设置此类是否应该自动执行 HTTP 重定向(响应代码为 3xx 的请求)。
 void setInstanceFollowRedirects(boolean followRedirects)
          设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向(响应代码为 3xx 的请求)。
 void setRequestMethod(String method)
          设置 URL 请求的方法, GET POST HEAD OPTIONS PUT DELETE TRACE 以上方法之一是合法的,具体取决于协议的限制。
abstract  boolean usingProxy()
          指示连接是否通过代理。

发送端:

public void requestFunction(HttpServletRequest request, HttpServletResponse response){
        try {
            request.setCharacterEncoding("utf-8");//设置请求的编码方式  
            response.setContentType("text/html;charset=utf-8");//设置返回时的编码方式  
            String http = "";
            URL url = new URL(http);//设置HTTP连接的URL地址
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();//生成HttpURLConnection连接
            httpURLConnection.setConnectTimeout(5000);//设置连接超时值
            httpURLConnection.setRequestMethod("post");//设置请求方式
            httpURLConnection.setDoOutput(true);//允许输出
            httpURLConnection.setDoInput(true);//允许输入
            httpURLConnection.setUseCaches(false);//不允许缓存
            OutputStream outs = httpURLConnection.getOutputStream();
            OutputStreamWriter sWriter = new OutputStreamWriter(outs,"UTF-8");//设置输出流
            sWriter.write(message);//写入缓冲流
            sWriter.flush();//刷新缓冲流
            sWriter.close();//关闭输出流
            outs.close();
            int responseCode = httpURLConnection.getResponseCode();//获取返回的请求码
            //表示请求成功
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream iStream = httpURLConnection.getInputStream();//获取服务端的输出流,得到返回数据
                //从字符输入流中读取文本,缓冲各个字符,从而实现字符、数组和行的高效读取。
                BufferedReader bReader = new BufferedReader(new InputStreamReader(iStream));
                String len;
                String str = "";
                while ((len=bReader.readLine()) != null) {
                    str += len;
                }
            }
        } catch (Exception e) {
        }
    }

服务端:

private void responseFunction(HttpServletRequest request, HttpServletResponse response) {
        request.setCharacterEncoding("utf-8");  
        response.setContentType("text/html;charset=utf-8");  
        String str=request.getParameter("xxx");//获得发送HTTP请求的参数   
        response.getWriter().write("{\"message\":\"success\"}");//向HTTP发送方返回响应数据  
    }

猜你喜欢

转载自www.cnblogs.com/lijianda/p/8962508.html