首页 / SERVLET / Servlet发送Http请求
Servlet发送Http请求
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Servlet发送Http请求,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2428字,纯文字阅读大概需要4分钟。
内容图文
今日遇到一个需求,android注册,短信验证码功能。
android请求我服务端,我请求tosms.cn发送验证码短信给android,于是需要在Servlet中发送Http请求
package org.helloword; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpInvoker { public static String STR_URL = "http://localhost:8080/JsonProject/servlet/JsonServlet?action_flag=person"; publicstaticvoid readContentFromGet() throws IOException { STR_URL = STR_URL + "¶m=paramstr"; URL getUrl = new URL(STR_URL); HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection(); connection.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader( connection.getInputStream())); System.out.println("=============get================"); String lines; while ((lines = reader.readLine()) != null) { System.out.println(lines); } reader.close(); connection.disconnect(); } publicstaticvoid readContentFromPost() throws IOException { URL postUrl = new URL(STR_URL); HttpURLConnection connection = (HttpURLConnection) postUrl .openConnection(); connection.setDoOutput(true); //post这个地方设置为true connection.setDoInput(true); connection.setRequestMethod("POST");// Post 请求不能使用缓存 connection.setUseCaches(false);// URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数 connection.setInstanceFollowRedirects(true);// 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的 // 意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode // 进行编码 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成, // 要注意的是connection.getOutputStream会隐式的进行connect。 connection.connect(); DataOutputStream out = new DataOutputStream(connection .getOutputStream()); out.flush(); out.close(); BufferedReader reader = new BufferedReader(new InputStreamReader( connection.getInputStream())); String line; System.out.println("=============post================"); while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); connection.disconnect(); } /** * @param args */publicstaticvoid main(String[] args) { try { readContentFromGet(); readContentFromPost(); } catch (IOException e) { e.printStackTrace(); } } //乱码用New String(xx.getByte("iso-8859-1"),"utf-8")解决 }
源代码http://down.51cto.com/data/2066142
原文:http://www.cnblogs.com/xiaoliu66007/p/4629754.html
内容总结
以上是互联网集市为您收集整理的Servlet发送Http请求全部内容,希望文章能够帮你解决Servlet发送Http请求所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。