javahttp访问接口
1. 怎么用java写一个http接口
一个servlet接口就可以了啊:
HTTP Header 请求实例
下面的实例使用 HttpServletRequest 的getHeaderNames()方法读取 HTTP 头信息。该方法返回一个枚举,包含与当前的 HTTP 请求相关的头信息。
一旦我们有一个枚举,我们可以以标准方式循环枚举,使用hasMoreElements()方法来确定何时停止,使用nextElement()方法来获取每个参数的名称。
//导入必需的java库
importjava.io.IOException;
importjava.io.PrintWriter;
importjava.util.Enumeration;
importjavax.servlet.ServletException;
importjavax.servlet.annotation.WebServlet;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
@WebServlet("/DisplayHeader")
//扩展HttpServlet类
{
//处理GET方法请求的方法
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException
{
//设置响应内容类型
response.setContentType("text/html;charset=UTF-8");
PrintWriterout=response.getWriter();
Stringtitle="HTTPHeader请求实例-菜鸟教程实例";
StringdocType=
"<!DOCTYPEhtml> ";
out.println(docType+
"<html> "+
"<head><metacharset="utf-8"><title>"+title+"</title></head> "+
"<bodybgcolor="#f0f0f0"> "+
"<h1align="center">"+title+"</h1> "+
"<tablewidth="100%"border="1"align="center"> "+
"<trbgcolor="#949494"> "+
"<th>Header名称</th><th>Header值</th> "+
"</tr> ");
EnumerationheaderNames=request.getHeaderNames();
while(headerNames.hasMoreElements()){
StringparamName=(String)headerNames.nextElement();
out.print("<tr><td>"+paramName+"</td> ");
StringparamValue=request.getHeader(paramName);
out.println("<td>"+paramValue+"</td></tr> ");
}
out.println("</table> </body></html>");
}
//处理POST方法请求的方法
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
doGet(request,response);
}
}
2. java 怎么调用http接口
方法:只要New一个Map,然后把要传递的参数以键值对的形式存入Map即可。privatevoidExample(){Stringurl=地址;Mapparam=newHashMap();p.put("ParamName","ParamValue");Stringhtml=this.visitURL(url,param);}
3. java http调用接口书写
rest接口的话可以使用
RestTemplate
Stringuri="http://example.com/hotels/1/bookings";
PostMethodpost=newPostMethod(uri);
Stringrequest=//createbookingrequestcontent
post.setRequestEntity(newStringRequestEntity(request));
httpClient.executeMethod(post);
if(HttpStatus.SC_CREATED==post.getStatusCode()){
Headerlocation=post.getRequestHeader("Location");
if(location!=null){
System.out.println("Creatednewbookingat:"+location.getValue());
}
}
api文档参考http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/remoting.html#rest-client-access
4. java如何创建一个简单的http接口
1.修改web.xml文件
<!-- 模拟HTTP的调用,写的一个http接口 --> <servlet> <servlet-name>TestHTTPServer</servlet-name> <servlet-class>com.atoz.http.SmsHTTPServer</servlet-class> </servlet> <servlet-mapping> <servlet-name>TestHTTPServer</servlet-name> <url-pattern>/httpServer</url-pattern> </servlet-mapping>
2.新建SmsHTTPServer.java文件
package com.atoz.http;
import java.io.IOException; import java.io.PrintWriter;
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import com.atoz.action.order.SendSMSAction; import com.atoz.util.SpringContextUtil;
public class SmsHTTPServer extends HttpServlet { private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); String content = request.getParameter("content"); //String content = new String(request.getParameter("content").getBytes("iso-8859-1"), "utf-8"); String mobiles = request.getParameter("mobiles"); String businesscode = request.getParameter("businesscode"); String businesstype = request.getParameter("businesstype"); if (content == null || "".equals(content) || content.length() <= 0) { System.out.println("http call failed,参数content不能为空,程序退出"); } else if (mobiles == null || "".equals(mobiles) || mobiles.length() <= 0) { System.out.println("http call failed,参数mobiles不能为空,程序退出"); } else { /*SendSMSServiceImpl send = new SendSMSServiceImpl();*/ SendSMSAction sendSms = (SendSMSAction) SpringContextUtil.getBean("sendSMS"); sendSms.sendSms(content, mobiles, businesscode, businesstype); System.out.println("---http call success---"); } out.close(); }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
3.调用http接口
String content = "测试"; content = URLEncoder.encode(content, "utf-8"); String url = "http://localhost:8180/atoz_2014/httpServer?content=" + content + "&mobiles=15301895007"; URL httpTest; try { httpTest = new URL(url); BufferedReader in; try { in = new BufferedReader(new InputStreamReader( httpTest.openStream())); String inputLine = null; String resultMsg = null; //得到返回信息的xml字符串 while ((inputLine = in.readLine()) != null) if(resultMsg != null){ resultMsg += inputLine; }else { resultMsg = inputLine; } in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
打字不易,望采纳,谢谢
5. java如何使用http方式调用第三方接口最好有代码~谢谢
星号是IP地址和端口号
public class HttpUtil {
private final static Log log = LogFactory.getLog(HttpUtil.class);
public static String doHttpOutput(String outputStr,String method) throws Exception {
Map map = new HashMap();
String URL = "http://****/interface/http.php" ;
String result = "";
InputStream is = null;
int len = 0;
int tmp = 0;
OutputStream output = null;
BufferedOutputStream objOutput = null;
String charSet = "gbk";
System.out.println("URL of fpcy request");
System.out.println("=============================");
System.out.println(URL);
System.out.println("=============================");
HttpURLConnection con = getConnection(URL);
try {
output = con.getOutputStream();
objOutput = new BufferedOutputStream(output);
objOutput.write(outputStr.getBytes(charSet));
objOutput.flush();
output.close();
objOutput.close();
int responseCode = con.getResponseCode();
if (responseCode == 200) {
is = con.getInputStream();
int dataLen = is.available();
int retry = 5;
while (dataLen == 0 && retry > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
dataLen = is.available();
retry--;
log.info("未获取到任何数据,尝试重试,当前剩余次数" + retry);
}
log.info("获取到报文单位数据长度:" + dataLen);
byte[] bytes = new byte[dataLen];
while ((tmp = is.read()) != -1) {
bytes[len++] = (byte) tmp;
if (len == dataLen) {
dataLen = bytes.length + dataLen;
byte[] newbytes = new byte[dataLen];
for (int i = 0; i < bytes.length; i++) {
newbytes[i] = bytes[i];
}
bytes = newbytes;
}
}
result = new String(bytes, 0, len, charSet);
} else {
String responseMsg = "调用接口失败,返回错误信息:" + con.getResponseMessage() + "(" + responseCode + ")";
System.out.println(responseMsg);
throw new Exception(responseMsg);
}
} catch (IOException e2) {
log.error(e2.getMessage(), e2);
throw new Exception("接口连接超时!,请检查网络");
}
con.disconnect();
System.out.println("=============================");
System.out.println("Contents of fpcy response");
System.out.println("=============================");
System.out.println(result);
Thread.sleep(1000);
return result;
}
private static HttpURLConnection getConnection(String URL) throws Exception {
Map map = new HashMap();
int rTimeout = 15000;
int cTimeout = 15000;
String method = "";
method = "POST";
boolean useCache = false;
useCache = false;
HttpURLConnection con = null;
try {
con = (HttpURLConnection) new URL(URL).openConnection();
} catch (IOException e) {
log.error(e.getMessage(), e);
throw new Exception("URL不合法!");
}
try {
con.setRequestMethod(method);
} catch (ProtocolException e) {
log.error(e.getMessage(), e);
throw new Exception("通信协议不合法!");
}
con.setConnectTimeout(cTimeout);
con.setReadTimeout(rTimeout);
con.setUseCaches(useCache);
con.setDoInput(true);
con.setDoOutput(true);
log.info("当前连接信息: URL:" + URL + "," + "Method:" + method
+ ",ReadTimeout:" + rTimeout + ",ConnectTimeOut:" + cTimeout
+ ",UseCaches:" + useCache);
return con;
}
public static void main(String[] args) throws Exception {
String xml="<?xml version=\"1.0\" encoding=\"GBK\" ?><document><txcode>101</txcode><netnumber>100001</netnumber>.........</document>";
response=HttpUtil.doHttpOutput(xml, "post");
JSONObject json= JSONObject.parseObject(response);
String retcode=json.getString("retcode");
调用这个类就能获得返回的参数。。over.
}
}
}
6. java如何调用对方http接口 新手虚心求教
importjava.io.BufferedReader;
importjava.io.DataOutputStream;
importjava.io.InputStreamReader;
importjava.net.HttpURLConnection;
importjava.net.URL;
importjava.net.URLEncoder;
publicclassDemoTest1{
publicstaticfinalStringGET_URL="http://112.4.27.9/mall-back/if_user/store_list?storeId=32";
//publicstaticfinalStringPOST_URL="http://112.4.27.9/mall-back/if_user/store_list";
//妙兜测试接口
publicstaticfinalStringPOST_URL="http://121.40.204.191:8180/mdserver/service/installLock";
/**
*接口调用GET
*/
(){
try{
URLurl=newURL(GET_URL);//把字符串转换为URL请求地址
HttpURLConnectionconnection=(HttpURLConnection)url.openConnection();//打开连接
connection.connect();//连接会话
//获取输入流
BufferedReaderbr=newBufferedReader(newInputStreamReader(connection.getInputStream(),"UTF-8"));
Stringline;
StringBuildersb=newStringBuilder();
while((line=br.readLine())!=null){//循环读取流
sb.append(line);
}
br.close();//关闭流
connection.disconnect();//断开连接
System.out.println(sb.toString());
}catch(Exceptione){
e.printStackTrace();
System.out.println("失败!");
}
}
/**
*接口调用POST
*/
(){
try{
URLurl=newURL(POST_URL);
//将url以open方法返回的urlConnection连接强转为HttpURLConnection连接(标识一个url所引用的远程对象连接)
HttpURLConnectionconnection=(HttpURLConnection)url.openConnection();//此时cnnection只是为一个连接对象,待连接中
//设置连接输出流为true,默认false(post请求是以流的方式隐式的传递参数)
connection.setDoOutput(true);
//设置连接输入流为true
connection.setDoInput(true);
//设置请求方式为post
connection.setRequestMethod("POST");
//post请求缓存设为false
connection.setUseCaches(false);
//设置该HttpURLConnection实例是否自动执行重定向
connection.setInstanceFollowRedirects(true);
//设置请求头里面的各个属性(以下为设置内容的类型,设置为经过urlEncoded编码过的from参数)
//application/x-javascripttext/xml->xml数据application/x-javascript->json对象application/x-www-form-urlencoded->表单数据
//;charset=utf-8必须要,不然妙兜那边会出现乱码【★★★★★】
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
//建立连接(请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)
connection.connect();
//创建输入输出流,用于往连接里面输出携带的参数,(输出内容为?后面的内容)
DataOutputStreamdataout=newDataOutputStream(connection.getOutputStream());
Stringapp_key="app_key="+URLEncoder.encode("","utf-8");//已修改【改为错误数据,以免信息泄露】
Stringagt_num="&agt_num="+URLEncoder.encode("10111","utf-8");//已修改【改为错误数据,以免信息泄露】
Stringpid="&pid="+URLEncoder.encode("BLZXA150401111","utf-8");//已修改【改为错误数据,以免信息泄露】
Stringdepartid="&departid="+URLEncoder.encode("10007111","utf-8");//已修改【改为错误数据,以免信息泄露】
Stringinstall_lock_name="&install_lock_name="+URLEncoder.encode("南天大门","utf-8");
Stringinstall_address="&install_address="+URLEncoder.encode("北京育新","utf-8");
Stringinstall_gps="&install_gps="+URLEncoder.encode("116.350888,40.011001","utf-8");
Stringinstall_work="&install_work="+URLEncoder.encode("小李","utf-8");
Stringinstall_telete="&install_telete="+URLEncoder.encode("13000000000","utf-8");
Stringintall_comm="&intall_comm="+URLEncoder.encode("一切正常","utf-8");
//格式parm=aaa=111&bbb=222&ccc=333&ddd=444
Stringparm=app_key+agt_num+pid+departid+install_lock_name+install_address+install_gps+install_work+install_telete+intall_comm;
//将参数输出到连接
dataout.writeBytes(parm);
//输出完成后刷新并关闭流
dataout.flush();
dataout.close();//重要且易忽略步骤(关闭流,切记!)
//System.out.println(connection.getResponseCode());
//连接发起请求,处理服务器响应(从连接获取到输入流并包装为bufferedReader)
BufferedReaderbf=newBufferedReader(newInputStreamReader(connection.getInputStream(),"UTF-8"));
Stringline;
StringBuildersb=newStringBuilder();//用来存储响应数据
//循环读取流,若不到结尾处
while((line=bf.readLine())!=null){
//sb.append(bf.readLine());
sb.append(line).append(System.getProperty("line.separator"));
}
bf.close();//重要且易忽略步骤(关闭流,切记!)
connection.disconnect();//销毁连接
System.out.println(sb.toString());
}catch(Exceptione){
e.printStackTrace();
}
}
publicstaticvoidmain(String[]args){
//httpURLConectionGET();
httpURLConnectionPOST();
}
}
7. java如何调用接口方式
计算机语言分类有很多,如C、C++、C#、Java、Php、Python等等,她们有各自的特性及擅长的领域,但她们各自又不是全能的。在一个稍微大型一点的项目都会用到多种语言共同完成,那么这些编程语言如何进行通信呢。什么意思呢,就是比如说我Java写的一个方法,其他编程语言要怎么去调用呢?这就是本文要探讨的问题了。
一般来说,方法层面的编程语言通信用的是网络接口形式,只暴露出形参和结果供别人调用。接口一般分为接口定义者和接口调用者,定义者可以规定接收参数的类型及返回形式,而接口定义者则只能完全按照接口定义者规定的参数进行访问。就叫是我们所说的webService(网络服务)。
以前的做法是利用XML作接口格式定义,然后通过Http做通讯和请求,如大名鼎鼎的SOAP,其实现在也是的,只不过现在流行RestFul风格的Rest接口形式,但用的还是XML+HTTP,那这两者有啥区别呢?最大的区别就是SOAP返回的主要是XML格式,有时还需要附带一些辅助文件,而Rest则还可以返回JSON类型的字符串,减少了很多繁乱的XML标签。
8. java如何调用对方http接口
你是指发送http请求吗,可以使用Apache 的 HttpClient
//构建HttpClient实例
CloseableHttpClienthttpclient=HttpClients.createDefault();//设置请求超时时间
RequestConfigrequestConfig=RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).setConnectionRequestTimeout(60000).build();//指定POST请求
HttpPosthttppost=newHttpPost(url);
httppost.setConfig(requestConfig);//包装请求体
List<NameValuePair>params=newArrayList<NameValuePair>();params.addAll(content);
HttpEntityrequest=newUrlEncodedFormEntity(params,"UTF-8");//发送请求
httppost.setEntity(request);
=httpclient.execute(httppost);//读取响应
HttpEntityentity=httpResponse.getEntity();Stringresult=null;if(entity!=null){
result=EntityUtils.toString(entity,"UTF-8");
}
9. java 开发HTTP接口
response.write("<?xml version=\"1.0\" encoding=\"utf-8\"?><root><proct><fruit name=\"orange\" /></proct></root>");这是最基本的实现.