java里不支持post请求,Java不发送HTTP POST请求

I'm implementing some simple java class in order to send an HTTP Request with POST method and also another java class in order to receive it.

The server works fine when I make a POST request by means of my browser(Chrome), or an application(I have used Postman in this case) but it ends up with problem when I send HTTP Request with java!

My sending HTTP class is "Sender.java", containing the following snippet:

String url = "http://localhost:8082/";

URL obj = new URL(url);

HttpURLConnection con = (HttpURLConnection) obj.openConnection();

// Setting basic post request

con.setRequestMethod("POST");

//con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

//con.setRequestProperty("Content-Type","text/plain");

// Send post request

con.setDoOutput(true);

OutputStream os = con.getOutputStream();

os.write("Just Some Text".getBytes("UTF-8"));

os.flush();

os.close();

//connect to the Server(resides at Server.java)

con.connect();

I have commented some lines of code setting Headers like "Accept-Language" and "Content-Type" because I don't know whether or not are these headers required for the java program to work out?

The server is another java program named "Server.java". Here is the snippet related to reading HTTP Request made by the Sender.java(if need be).

int servPort = 8082;

// Create a server socket to accept HTTP client connection requests

HttpServer server = HttpServer.create(new InetSocketAddress(servPort), 0);

System.out.println("server started at " + servPort);

server.createContext("/", new PostHandler());//PostHandler implements HttpHandler

server.setExecutor(null);

server.start();

All I want is to send a plaintext as the body of my HTTP Request with the Post method. I have read plenty of sites and even related questions at this site. But it still doesn't work out. In other words, whenever I create an HTTP Request from "Sender.java", nothing appears at "Server.java". I just want to know what's wrong with my snippets and how should I fix that?

解决方案

I tested this and it's working:

//Sender.java

String url = "http://localhost:8082/";

URL obj = new URL(url);

HttpURLConnection con = (HttpURLConnection) obj.openConnection();

con.setRequestMethod("POST");

con.setDoOutput(true);

OutputStream os = con.getOutputStream();

os.write("Just Some Text".getBytes("UTF-8"));

os.flush();

int httpResult = con.getResponseCode();

con.disconnect();

As you can see, connect is not necessary. The key line is

int httpResult = con.getResponseCode();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值