如何利用JAVA写一个简单的get或者post的接口?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何利用JAVA写一个简单的get或者post的接口?相关的知识,希望对你有一定的参考价值。
如何利用JAVA写一个简单的get或者post的接口?
参考技术A WebService很简单,无论你想发布服务还是调取别人的服务。 参考技术B java中的servlet 参考技术C import java.io.IOException;import javax.servlet.*;
import javax.servlet.http.*;
public class JavaServletSample extends HttpServlet
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
// TODO
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
// TODO
最简单的一种。本回答被提问者采纳 参考技术D package com.huaye.network.util;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
public class HttpUtil
/**
* http������ݣ�Ĭ�Ϸ��ص����ΪUTF-8����
*
* @param url
* url��ַ
* @param method
* �ύ��ʽ
* @return
* @throws IOException
*/
public static String getUrl(String url) throws IOException
try
HttpGet request = new HttpGet(url);
HttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT, 20000); // ��������ʱʱ��
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000); // ��ȡ��ʱ
HttpResponse response = httpClient.execute(request);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
String result = EntityUtils.toString(response.getEntity(), "utf-8");
//httpClient.getConnectionManager().releaseConnection(conn, validDuration, timeUnit)
return result;
else
return "kong";
catch (Exception e)
// TODO: handle exception
System.out.println(e);
e.printStackTrace();
return "kong";
/**
* post�ύ��
*
* @param url
* �ύ��ַ
* @param params
* ����
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public static String postUrl(String url, Map<String, String> params)
throws ClientProtocolException, IOException
return postUrl(url, params, "UTF-8");
/**
* post�ύ��
*
* @param url
* �ύ��ַ
* @param params
* ����
* @param encoding
* ������
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public static String postUrl(String url, Map<String, String> params,
String encoding) throws ClientProtocolException, IOException
List<NameValuePair> param = new ArrayList<NameValuePair>(); // ����
// param.add(new BasicNameValuePair("par", "request-post"));
// //��������Ҳ�֪���Dz��Ƿ�Ҫ�����
// ��Ӳ��
Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
while (iterator.hasNext())
Entry<String, String> entry = iterator.next();
param.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
HttpPost request = new HttpPost(url);
HttpEntity entity = new UrlEncodedFormEntity(param, encoding);
request.setEntity(entity);
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT, 5000); // ��������ʱʱ��
client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000); // ��ȡ��ʱ
HttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
return EntityUtils.toString(response.getEntity(), "utf-8");
else
return "null";
第5个回答 2014-08-08 你是想调用别人接口,还是接口被人调用 ?追问
被别人调用
追答很简单啊,比如直接写个servlet就行,接收参数可以是json什么的,返回json也行!访问地址就是你的项目地址+配置的servlet名称+参数。
Java Socket 实现HTTP与HTTPS协议发送POST/GET请求
JAVA Socket 实现HTTP与HTTPS客户端发送POST与GET方式请求哇,一看标题怎么这么长啊,其实意思很简单,哥讨厌用HTTP Client做POST与GET提交觉得那个毕竟是别人写得API库,所以我就自己实现了一个简单的HTTP客户端,支持POST方式提交数据,GET方式查询数据,是测试Restful API比较方便点,然后支持form与JSON两种方式提交数据,当然也支持返回数据为JSON格式.当然这些东西都是基于JAVA Socket直接完成的,不借助任何第三方的库,主要是JDK的API其实已经够用啦. 当然我也没有用URLConnect这个东西,毕竟它在Socket基础上又包装了一下,有违我写这篇文章的目的.
好啦,讲完理由,下面就说说要怎么样才能实现啊,光说不练假把式啊!大致分了几个步骤
一:当然是要知道HTTP协议,知道常用的HTTP请求头,比如Host, Accept, Content-Type 知道HTTP协议支持的方法,常用有GET/POST/PUT/DELETE等如果不知道,也不用担心,我保证你读完这篇文章,你就知道一些啦,当然有个最好的参考文档就是HTTP相关的RFC文档,认真读一下肯定解决你自己心中的HTTP那些疑惑
二: 知道发送HTTP GET与POST格式很重要, 固定的格式如下:
[REQUEST]<SP><URL><SP>[HTTP VERSION]<CLRF>
[REQUEST HEADER: ]<SP>[VALUE]<CLRF>
可以有多个请求头
最后<CLRF>
发送完HTTP请求头部以后, 针对不同请求如POST要发送内容部分,发送完成以后同样,以<CLRF>结尾.
解释: <SP>表示空格, <CLRF>表示回车换行JAVA中表示为”\\r\\n”REQUEST表示HTTP请求命令,可以为POST, GET, PUT, DELETE等之一,HTTP VERSION的常见可能值为HTTP/1.1或者HTTP/1.0
三: 如果1与2的知识你都具备了,下面就来介绍一下JAVA Socket的相关知识,如何创建一个JAVA客户端套接字Socket s = new Socket()如此即可,简单吧!如何连接到远程的主机与端口, 当提供URL字符串时候,可以这么做
URL url = new URL(“http://blog.csdn.net/jia20003”);
String host = url.getHost;
int port = url.getDefaultPort();
SocketAddress dest = new InetSocketAddress(this.host, this.port);
s.connect(dest);
即可连接到远程主机,下面就可以请求文章内容了, 也很容易的
[java] view plain copy
- String path = "/jia20003/article/details/16908661";
- SocketAddress dest = new InetSocketAddress(this.host, this.port);
- socket.connect(dest);
- OutputStreamWriter streamWriter = new OutputStreamWriter(socket.getOutputStream());
- bufferedWriter = new BufferedWriter(streamWriter);
- bufferedWriter.write("GET " + path + " HTTP/1.1\\r\\n");
- bufferedWriter.write("Host: " + this.host + "\\r\\n");
- bufferedWriter.write("\\r\\n");
- bufferedWriter.flush();
四:关于HTTP与HTTPS
HTTP协议是位于第四层协议TCP之上完成的应用层协议, 端到端都是明文传送,别人一旦网络抓包以后都可以看到你的提交与请求数据,这个好像不太安全. HTTP协议的默认端口是80这个是RFC文档声明的,属于官方标准,没什么道理可以讲.HTTPS是基于SSL加密传输的,这样别人截获你的数据包破解的概率要小一点,比HTTP安全一点,其默认端口是443, 好像QQ邮箱与谷歌的WEB Mail邮箱都是基于HTTPS. 但是HTTPS通信方式只是传输数据加密,都客户端来说是透明的,它还是一样要遵守HTTP协议规范来发送POST与GET请求等.完整的测试程序如下:
http协议实现:
[java] view plain copy- package com.gloomyfish.http.client;
- import java.io.BufferedInputStream;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- import java.net.InetSocketAddress;
- import java.net.Socket;
- import java.net.SocketAddress;
- import java.net.URLEncoder;
- public class TestDemo
- private int port;
- private String host;
- private Socket socket;
- private BufferedReader bufferedReader;
- private BufferedWriter bufferedWriter;
- public TestDemo(String host, int port)
- socket = new Socket();
- this.host = host;
- this.port = port;
- public void sendGet() throws IOException
- String path = "/zhigang/getDemo.php";
- SocketAddress dest = new InetSocketAddress(this.host, this.port);
- socket.connect(dest);
- OutputStreamWriter streamWriter = new OutputStreamWriter(socket.getOutputStream());
- bufferedWriter = new BufferedWriter(streamWriter);
- bufferedWriter.write("GET " + path + " HTTP/1.1\\r\\n");
- bufferedWriter.write("Host: " + this.host + "\\r\\n");
- bufferedWriter.write("\\r\\n");
- bufferedWriter.flush();
- BufferedInputStream streamReader = new BufferedInputStream(socket.getInputStream());
- bufferedReader = new BufferedReader(new InputStreamReader(streamReader, "utf-8"));
- String line = null;
- while((line = bufferedReader.readLine())!= null)
- System.out.println(line);
- bufferedReader.close();
- bufferedWriter.close();
- socket.close();
- public void sendPost() throws IOException
- String path = "/zhigang/postDemo.php";
- String data = URLEncoder.encode("name", "utf-8") + "=" + URLEncoder.encode("gloomyfish", "utf-8") + "&" +
- URLEncoder.encode("age", "utf-8") + "=" + URLEncoder.encode("32", "utf-8");
- // String data = "name=zhigang_jia";
- SocketAddress dest = new InetSocketAddress(this.host, this.port);
- socket.connect(dest);
-
以上是关于如何利用JAVA写一个简单的get或者post的接口?的主要内容,如果未能解决你的问题,请参考以下文章Java Socket 实现HTTP与HTTPS协议发送POST/GET请求
Java爬虫利用GET和POST发送请求,获取服务器返回信息