java 实现http协议发送接收数据

java模拟 post/get方式发送数据   main方法中用的是post

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;


public class httpurl {

    private static final String TAG = "netUtils";

    /**
     * 使用post方式登陆
     *
     * @param username
     * @param password
     * @return
     */
    public static void main(String []args){
        httpurl test=new httpurl();
        test.loginOfPost("niha","qwer1234");
    }
    public static String loginOfPost(String username, String password) {
        HttpURLConnection conn = null;
        try {
            // 创建一个URL对象
            URL mURL = new URL("http://localhost:12001");
            // 调用URL的openConnection()方法,获取HttpURLConnection对象
            conn = (HttpURLConnection) mURL.openConnection();

            conn.setRequestMethod("POST");// 设置请求方法为post
           /* conn.setReadTimeout(5000);// 设置读取超时为5秒
            conn.setConnectTimeout(10000);// 设置连接网络超时为10秒*/
            conn.setDoOutput(true);// 设置此方法,允许向服务器输出内容

            int len=0;
            String path="E:\\private_project\\github_project\\nsar\\test.txt";
            // post请求的参数
            byte[] buf= new byte[10240];
            FileInputStream fis=new FileInputStream(path);
            while((len = fis.read(buf)) != -1){
                System.out.print(len);
            }
//            String data = "username=" + username + "&password=" + password;
            // 获得一个输出流,向服务器写数据,默认情况下,系统不允许向服务器输出内容
            OutputStream out = conn.getOutputStream();// 获得一个输出流,向服务器写数据
//            out.write(data.getBytes());
            out.write(buf);
            out.flush();
            out.close();

            int responseCode = conn.getResponseCode();// 调用此方法就不必再使用conn.connect()方法
            if (responseCode == 200) {

                InputStream is = conn.getInputStream();
                String state = getStringFromInputStream(is);
                return state;
            } else {
//                Log.i(TAG, "访问失败" + responseCode);
                System.out.print("访问失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();// 关闭连接
            }
        }

        return null;
    }

    /**
     * 使用get方式登陆
     *
     * @param username
     * @param password
     * @return
     */
    public static String loginOfGet(String username, String password) {
        HttpURLConnection conn = null;

        String data = "username=" + URLEncoder.encode(username) + "&password="+ URLEncoder.encode(password);
        String url = "http://192.168.0.100:8080/android/servlet/LoginServlet?"+ data;
        try {
            // 利用string url构建URL对象
            URL mURL = new URL(url);
            conn = (HttpURLConnection) mURL.openConnection();

            conn.setRequestMethod("GET");
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(10000);

            int responseCode = conn.getResponseCode();
            if (responseCode == 200) {

                InputStream is = conn.getInputStream();
                String state = getStringFromInputStream(is);
                return state;
            } else {
//                Log.i(TAG, "访问失败" + responseCode);
                System.out.print("访问失败");

            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            if (conn != null) {
                conn.disconnect();
            }
        }

        return null;
    }

    /**
     * 根据流返回一个字符串信息         *
     * @param is
     * @return
     * @throws IOException
     */
    private static String getStringFromInputStream(InputStream is)
            throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        // 模板代码 必须熟练
        byte[] buffer = new byte[1024];
        int len = -1;
        // 一定要写len=is.read(buffer)
        // 如果while((is.read(buffer))!=-1)则无法将数据写入buffer中
        while ((len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
        }
        is.close();
        String state = os.toString();// 把流中的数据转换成字符串,采用的编码是utf-8(模拟器默认编码)
        os.close();
        return state;
    }
}


java 模拟服务器端接收post/get数据  实现时不需要向客户端返回数据,只需要接受客户端发过来的数据 所以response 注释掉了

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by lpeiz on 2016/9/26.
 */
public class Server {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(12001);
//            System.out.println("HTTP Server (only POST implemented) is ready and is listening on Port Number 12001 \n");
            while(true) {
                Socket clientSocket = serverSocket.accept();
//                System.out.println(clientSocket.getInetAddress().toString() + " " + clientSocket.getPort());
                BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
//                OutputStream out = clientSocket.getOutputStream();
                String temp;
                int i=1001;
                while((temp=in.readLine()) != null)
                    System.out.println(temp+i++);
//                String response = "HTTP/1.1 200 OK\n\r";
//                response = response + "Date: Fri, 04 May 2001 20:08:11 GMT\n\r";
//                response = response + "Server: Sanjits Server\n\r";
//                response = response + "Connection: close\n\r";
//                response = response + "1";
//                byte[] bytes = response.getBytes();
//                byte[]bytes=new byte[1024];
//                out.write(bytes);
//                out.flush();
                in.close();
//                out.close();
            }
        } catch(Exception e) {
            System.out.println("ERROR: " + e.getMessage());
            System.exit(1);
        }}}


国庆节前看了一个案例  但是跑的时候发现是错误的 13年前的帖子,现在还用这计数也确实该多学点先进的技术了

https://coderanch.com/t/205623/java/Java-Http-Server-Java-Http

对客户端的程序参照网上找到的其他成功的程序 改造了一下,加了两行发现成功了。。。

 con.setReadTimeout(5000);// 设置读取超时为5秒
            con.setConnectTimeout(10000);// 设置连接网络超时为10秒
就是这个控制时间的两行,还没搞清楚为什么。可能是类似jdbc连接的时候的语句执行之后的刷新问题

public class Client {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://localhost:12001");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setDoOutput(true);
//            con.setDoInput(true);
            con.setRequestMethod("POST");
//            con.setUseCaches(false);
            con.setReadTimeout(5000);// 设置读取超时为5秒
            con.setConnectTimeout(10000);// 设置连接网络超时为10秒

            String test = "<name>Hello</name>";
            byte[] bytes = test.getBytes();

//            con.setRequestProperty("Content-type", "text/html");

            OutputStream out = con.getOutputStream();

            out.write(bytes);
            out.flush();
            out.close();
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String temp;
            while((temp = in.readLine()) != null)
                System.out.println(temp);
//            out.close();
            in.close();
            con.disconnect();
        } catch(Exception e) {
            e.printStackTrace();
            System.exit(1);}}}





  • 2
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java是一种流行的编程语言,它可以轻松地实现后台发送及接收JSON数据。下面是一个简单的示例: 发送JSON数据: 要发送JSON数据,我们需要创建一个HTTP请求,并将JSON数据作为请求的主发送。以下是一个示例代码: ```java URL url = new URL("http://example.com/api"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); conn.setDoOutput(true); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("name", "John"); jsonObject.addProperty("age", 30); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(jsonObject.toString()); writer.flush(); writer.close(); ``` 在这个例子中,我们首先创建了一个URL对象,它指向我们要发送请求的API。然后,我们创建了一个HttpURLConnection对象,它允许我们使用HTTP协议进行数据传输。我们设置了请求的方法为POST,并且设置了请求头的Content-Type为application/json。在设置完请求头之后,我们将请求主设置为一个JSON对象,并将其作为字符串发送。最后,我们关闭了输出流。 接收JSON数据: 要在Java中接收JSON数据,我们需要从HTTP响应中获取JSON字符串,然后将其转换为Java对象。以下是一个示例代码: ```java URL url = new URL("http://example.com/api"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String output; StringBuilder sb = new StringBuilder(); while ((output = br.readLine()) != null) { sb.append(output); } JsonObject jsonObject = new JsonParser().parse(sb.toString()).getAsJsonObject(); String name = jsonObject.get("name").getAsString(); int age = jsonObject.get("age").getAsInt(); ``` 在这个例子中,我们首先创建了一个URL对象,它指向我们要请求JSON数据的API。然后,我们创建了一个HttpURLConnection对象,并将其请求方法设置为GET。我们设置请求头的Accept为application/json,指示我们需要接收JSON格式的数据。然后,我们使用缓冲读取器从输入流中读取响应,并将其附加到一个字符串构建器中。在读取完整个响应之后,我们使用Gson库将JSON字符串转换为一个JsonObject对象。最后,我们从JsonObject中获取名字和年龄,并将它们作为Java字符串和整数变量存储起来。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值