javahttp请求resteasyclient的简单介绍

本文目录一览:

如何在Java中 提供 RESTful Web 服务

通过REST风格体系架构,请求和响应都是基于资源表示的传输来构建的。资源是通过全局ID来标识的,这些ID一般使用的是一个统一资源标识符(URI)。客户端应用使用HTTP方法(如,GET、POST、PUT或DELETE)来操作一个或多个资源。通常,GET是用于获取或列出一个或多个资源,POST用于创建,PUT用于更新或替换,而DELETE则用于删除资源。

例如,GET http //host/context/employees/12345将获取ID为12345的员工的表示。这个响应表示可以是包含详细的员工信息的XML或ATOM,或者是具有更好UI的JSP/HTML页面。您看到哪种表示方式取决于服务器端实现和您的客户端请求的MIME类型。

RESTful Web Service是一个使用HTTP和REST原理实现的Web Service。通常,一个RESTful Web Service将定义基本资源URI、它所支持的表示/响应MIME,以及它所支持的操作。

本文将介绍如何使用Spring创建Java实现的服务器端RESTful Web Services。这个例子将使用浏览器、curl和Firefox插件RESTClient作为发出请求的客户端。

本文假定您是熟悉REST基本知识的。

Spring 3的REST支持

在Spring框架支持REST之前,人们会使用其他几种实现技术来创建Java RESTful Web Services,如Restlet、RestEasy和Jersey。Jersey是其中最值得注意的,它是JAX-RS(JSR 311)的参考实现。

Spring是一个得到广泛应用的Java EE框架,它在版本3以后就增加了RESTful Web Services开发的支持。虽然,对REST的支持并不是JAX-RS的一种实现,但是它具有比标准定义更多的特性。REST支持被无缝整合到Spring的MVC层,它可以很容易应用到使用Spring构建的应用中。

Spring REST支持的主要特性包括:

注释,如@RequestMapping 和 @PathVariable,支持资源标识和URL映射

ContentNegotiatingViewResolver支持为不同的MIME/内容类型使用不同的表示方式

使用相似的编程模型无缝地整合到原始的 MVC 层

创建一个示例RESTful Web Service

本节中的例子将演示Spring 3环境的创建过程,并创建一个可以部署到Tomcat中的“Hello World”应用。然后我们再完成一个更复杂的应用来了解Spring 3 REST支持的重要概念,如多种MIME类型表示支持和JAXB支持。另外,本文还使用一些代码片断来帮助理解这些概念。

Hello World:使用Spring 3 REST支持

要创建这个例子所使用的开发环境,您需要:

IDE:Eclipse IDE for JEE (v3.4+)

Java SE5 以上

Web 容器:Apache Tomcat 6.0(Jetty或其他容器也可)

Spring 3框架(v3.0.3是本文编写时的最新版本)

其他程序库:JAXB 2、JSTL、commons-logging

在 Eclipse 中创建一个Web应用,然后设置Tomcat 6作为它的运行环境。然后,您需要设置web.xml文件来激活Spring

WebApplicationContext。这个例子将Spring bean配置分成两个文件:rest-servlet.xml 包含与MVC/REST有关的配置,rest-context.xml包含服务级别的配置(如数据源 beans)。清单 1 显示了web.xml中的Spring配置的部分。

清单 1. 在web.xml中激活Spring WebApplicationContext

以下是引用片段:

contextConfigLocation

/WEB-INF/rest-context.xml

!– This listener will load other application context file in addition to

rest-servlet.xml —

org.springframework.web.context.ContextLoaderListener

rest

org.springframework.web.servlet.DispatcherServlet

1

rest

/service/*

在rest-servlet.xml文件中创建Spring MVC的相关配置(Controller、View、View Resolver)。清单 2 显示了其中最重要的部分。

清单 2. 在rest-servlet.xml文件中创建Spring MVC配置

以下是引用片段:

bean class=”org.springframework.web.servlet.mvc.annotation

.DefaultAnnotationHandlerMapping” /

bean class=”org.springframework.web.servlet.mvc.annotation

.AnnotationMethodHandlerAdapter” /

bean id=”jaxbMarshaller”

class=”org.springframework.oxm.jaxb.Jaxb2Marshaller”

dw.spring3.rest.bean.Employee

dw.spring3.rest.bean.EmployeeList

bean id=”employees” class=

“org.springframework.web.servlet.view.xml.MarshallingView”

bean id=”viewResolver” class=

“org.springframework.web.servlet.view.BeanNameViewResolver” /

上面的代码中:

Component-scan启用对带有Spring注释的类进行自动扫描,在实践中,它将检查控制器类中所定义的@Controller注释。

DefaultAnnotationHanlderMappings和AnnotationMethodHandlerAdapter使用@ReqeustMapping注释的类或函数的beans由Spring处理这个注释将在下一节进行详细介绍。

Jaxb2Mashaller定义使用JAXB 2进行对象XML映射(OXM)的编组器(marshaller)和解组器(unmarshaller )

MashallingView定义一个使用Jaxb2Mashaller的XML表示view

BeanNameViewResolver使用用户指定的bean名称定义一个视图解析器

本例将使用名为“employees”的MarshallingView。

这样就完成了Spring的相关配置。下一步是编写一个控制器来处理用户请求。清单3显示的是控制器类。

java 调用 rest 接口 怎么写请求行的信息

package com.demo;

import jaimg id=”selectsearch-icon” src=”” alt=”搜索”va.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import javax.xml.bind.DatatypeConverter;

import org.apache.http.HttpResponse;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.DefaultHttpClient;

public class restTest {

public static voidmain(String[] args) {

try {

DefaultHttpClient Client = newDefaultHttpClient();

HttpGet httpGet = newHttpGet(“你的地址”);

String encoding =DatatypeConverter.printBase64Binary(“admin:admin”.getBytes(“UTF-8”));

httpGet.setHeader(“Authorization”, “Basic ” +encoding);

HttpResponse response = Client.execute(httpGet);

System.out.println(“response =” + response);

BufferedReader breader = newBufferedReader(new InputStreamReader(response.getEntity().getContent()));

StringBuilder responseString = newStringBuilder();

String line = “”;

while ((line = breader.readLine()) !=null) {

responseString.append(line);

}

breader.close();

String repsonseStr =responseString.toString();

System.out.println(“repsonseStr =” + repsonseStr);

} catch (IOException e) {

e.printStackTrace();

}

}

}

ResteasyClient 怎么设置请求的编码格式

package com.supermap.earth.rims.util;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.UnsupportedEncodingException;

import java.net.MalformedURLException;

import java.net.URL;

import java.net.URLConnection;

import java.util.ArrayList;

import java.util.List;

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.HttpStatus;

import org.apache.http.HttpVersion;

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.HttpPost;

import org.apache.http.conn.ClientConnectionManager;

import org.apache.http.conn.params.ConnManagerParams;

import org.apache.http.conn.scheme.PlainSocketFactory;

import org.apache.http.conn.scheme.Scheme;

import org.apache.http.conn.scheme.SchemeRegistry;

import org.apache.http.conn.ssl.SSLSocketFactory;

import org.apache.http.entity.mime.MultipartEntity;

import org.apache.http.entity.mime.content.FileBody;

import org.apache.http.entity.mime.content.StringBody;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;

import org.apache.http.params.BasicHttpParams;

import org.apache.http.params.HttpConnectionParams;

import org.apache.http.params.HttpParams;

import org.apache.http.params.HttpProtocolParams;

import org.apache.http.protocol.HTTP;

import org.apache.http.util.EntityUtils;

public class CustomerHttpClient {

private static final String TAG = “CustomerHttpClient”;

private static final String ENCODING = HTTP.UTF_8;

private static HttpClient customerHttpClient;

private CustomerHttpClient() {

}

public static synchronized HttpClient getHttpClient() {

if (null == customerHttpClient) {

HttpParams params = new BasicHttpParams();

// 设置一些基本参数

HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

HttpProtocolParams.setContentCharset(params, ENCODING);

HttpProtocolParams.setUseExpectContinue(params, true);

HttpProtocolParams

.setUserAgent(

params,

“Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) “

+ “AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1”);

ConnManagerParams.setTimeout(params, 5000);

HttpConnectionParams.setConnectionTimeout(params, 5000);

HttpConnectionParams.setSoTimeout(params, 4000);

SchemeRegistry schReg = new SchemeRegistry();

schReg.register(new Scheme(“http”, PlainSocketFactory

.getSocketFactory(), 80));

schReg.register(new Scheme(“https”, SSLSocketFactory

.getSocketFactory(), 443));

ClientConnectionManager conMgr = new ThreadSafeClientConnManager(

params, schReg);

customerHttpClient = new DefaultHttpClient(conMgr, params);

}

return customerHttpClient;

}

public static String post(String url, NameValuePair… params) {

try {

// 编码参数

ListNameValuePair formparams = new ArrayListNameValuePair(); // 请求参数

for (NameValuePair p : params) {

formparams.add(p);

}

UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams,

ENCODING);

// 创建POST请求

HttpPost request = new HttpPost(url);

request.setEntity(entity);

// 发送请求

HttpClient client = getHttpClient();

HttpResponse response = client.execute(request);

if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {

throw new RuntimeException(“请求失败”);

}

HttpEntity resEntity = response.getEntity();

return (resEntity == null) ? null : EntityUtils.toString(resEntity,

ENCODING);

} catch (UnsupportedEncodingException e) {

return null;

} catch (ClientProtocolException e) {

return null;

} catch (IOException e) {

throw new RuntimeException(“连接失败”, e);

}

}

/**

* httpclient不直接支持及mime multipart方式上传附件,需要引入第三方类库

* D:\Downloads\android\apache mime\apache-mime4j-0.6.jar

* D:\Downloads\android\apache mime\commons-io-2.1.jar

* D:\Downloads\android\apache mime\httpmime-4.0.jar

*/

public static boolean httpPostUpload(String serverUrl, String headContent,

String fileName) {

try {

HttpClient client = new DefaultHttpClient();

HttpPost post = new HttpPost(serverUrl);

// multipart实体

MultipartEntity entity = new MultipartEntity();

entity.addPart(“picMsg”, new StringBody(headContent));

entity.addPart(“pic”, new FileBody(new File(fileName)));

post.setEntity(entity);

HttpResponse resp = client.execute(post);

if (resp.getStatusLine().getStatusCode() == 200) {

return true;

}

} catch (Exception e) {

e.printStackTrace();

}

return false;

}

// ////////////////////////////////////////////////////////////////

/**

* 获取图片流

*

* @param uri

* 图片地址

*

* @return

* @throws MalformedURLException

*/

public static InputStream GetImageByUrl(String uri)

throws MalformedURLException {

URL url = new URL(uri);

URLConnection conn;

InputStream is;

try {

conn = url.openConnection();

conn.connect();

is = conn.getInputStream();

return is;

} catch (IOException e) {

e.printStackTrace();

}

return null;

}

public static void saveFile(InputStream fis, String saveDir)

throws Exception {

FileOutputStream fos = new FileOutputStream(new File(saveDir));

byte[] b = new byte[1];

while (fis.read(b) != -1) {

fos.write(b);

fos.flush();

}

fis.close();

fos.close();

}

}

如何在java中发起http和https请求

1.写http请求方法

[java] view plain copy

//处理http请求 requestUrl为请求地址 requestMethod请求方式,值为”GET”或”POST”

public static String httpRequest(String requestUrl,String requestMethod,String outputStr){

StringBuffer buffer=null;

try{

URL url=new URL(requestUrl);

HttpURLConnection conn=(HttpURLConnection)url.openConnection();

conn.setDoOutput(true);

conn.setDoInput(true);

conn.setRequestMethod(requestMethod);

conn.connect();

//往服务器端写内容 也就是发起http请求需要带的参数

if(null!=outputStr){

OutputStream os=conn.getOutputStream();

os.write(outputStr.getBytes(“utf-8”));

os.close();

}

//读取服务器端返回的内容

InputStream is=conn.getInputStream();

InputStreamReader isr=new InputStreamReader(is,”utf-8″);

BufferedReader br=new BufferedReader(isr);

buffer=new StringBuffer();

String line=null;

while((line=br.readLine())!=null){

buffer.append(line);

}

}catch(Exception e){

e.printStackTrace();

}

return buffer.toString();

}

2.测试。

[java] view plain copy

public static void main(String[] args){

String s=httpRequest(“”,”GET”,null);

System.out.println(s);

}

输出结果为的源代码,说明请求成功。

注:1).第一个参数url需要写全地址,即前边的http必须写上,不能只写这样的。

2).第二个参数是请求方式,一般接口调用会给出URL和请求方式说明。

3).第三个参数是我们在发起请求的时候传递参数到所要请求的服务器,要传递的参数也要看接口文档确定格式,一般是封装成json或xml.

4).返回内容是String类,但是一般是有格式的json或者xml。

二:发起https请求。

1.https是对链接加了安全证书SSL的,如果服务器中没有相关链接的SSL证书,它就不能够信任那个链接,也就不会访问到了。所以我们第一步是自定义一个信任管理器。自要实现自带的X509TrustManager接口就可以了。

[java] view plain copy

import java.security.cert.CertificateException;

import java.security.cert.X509Certificate;

import javax.net.ssl.X509TrustManager;

public class MyX509TrustManager implements X509TrustManager {

@Override

public void checkClientTrusted(X509Certificate[] chain, String authType)

throws CertificateException {

// TODO Auto-generated method stub

}

@Override

public void checkServerTrusted(X509Certificate[] chain, String authType)

throws CertificateException {

// TODO Auto-generated method stub

}

@Override

public X509Certificate[] getAcceptedIssuers() {

// TODO Auto-generated method stub

return null;

}

}

注:1)需要的包都是java自带的,所以不用引入额外的包。

2.)可以看到里面的方法都是空的,当方法为空是默认为所有的链接都为安全,也就是所有的链接都能够访问到。当然这样有一定的安全风险,可以根据实际需要写入内容。

2.编写https请求方法。

[java] view plain copy

/*

* 处理https GET/POST请求

* 请求地址、请求方法、参数

* */

public static String httpsRequest(String requestUrl,String requestMethod,String outputStr){

StringBuffer buffer=null;

try{

//创建SSLContext

SSLContext sslContext=SSLContext.getInstance(“SSL”);

TrustManager[] tm={new MyX509TrustManager()};

//初始化

sslContext.init(null, tm, new java.security.SecureRandom());;

//获取SSLSocketFactory对象

SSLSocketFactory ssf=sslContext.getSocketFactory();

URL url=new URL(requestUrl);

HttpsURLConnection conn=(HttpsURLConnection)url.openConnection();

conn.setDoOutput(true);

conn.setDoInput(true);

conn.setUseCaches(false);

conn.setRequestMethod(requestMethod);

//设置当前实例使用的SSLSoctetFactory

conn.setSSLSocketFactory(ssf);

conn.connect();

//往服务器端写内容

if(null!=outputStr){

OutputStream os=conn.getOutputStream();

os.write(outputStr.getBytes(“utf-8”));

os.close();

}

//读取服务器端返回的内容

InputStream is=conn.getInputStream();

InputStreamReader isr=new InputStreamReader(is,”utf-8″);

BufferedReader br=new BufferedReader(isr);

buffer=new StringBuffer();

String line=null;

while((line=br.readLine())!=null){

buffer.append(line);

}

}catch(Exception e){

e.printStackTrace();

}

return buffer.toString();

}

可见和http访问的方法类似,只是多了SSL的相关处理。

3.测试。先用http请求的方法访问,再用https的请求方法访问,进行对比。

http访问:

[java] view plain copy

public static void main(String[] args){

String s=httpRequest(“”,”GET”,null);

System.out.println(s);

}

结果为:

https访问:

[java] view plain copy

public static void main(String[] args){

String s=httpsRequest(“”,”GET”,null);

System.out.println(s);

}

结果为:

可见https的链接一定要进行SSL的验证或者过滤之后才能够访问。

三:https的另一种访问方式——导入服务端的安全证书。

1.下载需要访问的链接所需要的安全证书。 以这个网址为例。

1)在浏览器上访问。

2)点击上图的那个打了×的锁查看证书。

3)选择复制到文件进行导出,我们把它导入到java项目所使用的jre的lib文件下的security文件夹中去,我的是这个路径。D:\Program Files (x86)\Java\jre8\lib\security

注:中间需要选导出格式,就选默认的就行,还需要命名,我命名的是12306.

2.打开cmd,进入到java项目所使用的jre的lib文件下的security目录。

3.在命令行输入 Keytool -import -alias 12306 -file 12306.cer -keystore cacerts

4.回车后会让输入口令,一般默认是changeit,输入时不显示,输入完直接按回车,会让确认是否信任该证书,输入y,就会提示导入成功。

5.导入成功后就能像请求http一样请求https了。

测试:

[java] view plain copy

public static void main(String[] args){

String s=httpRequest(“”,”GET”,null);

System.out.println(s);

}

结果:

现在就可以用http的方法请求https了。

注:有时候这一步还是会出错,那可能是jre的版本不对,我们右键run as——run configurations,选择证书所在的jre之后再运行。

原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/278380.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
小蓝小蓝
上一篇 2024-12-19 13:21
下一篇 2024-12-19 13:21

相关推荐

  • Python简单数学计算

    本文将从多个方面介绍Python的简单数学计算,包括基础运算符、函数、库以及实际应用场景。 一、基础运算符 Python提供了基础的算术运算符,包括加(+)、减(-)、乘(*)、除…

    编程 2025-04-29
  • Python满天星代码:让编程变得更加简单

    本文将从多个方面详细阐述Python满天星代码,为大家介绍它的优点以及如何在编程中使用。无论是刚刚接触编程还是资深程序员,都能从中获得一定的收获。 一、简介 Python满天星代码…

    编程 2025-04-29
  • Python海龟代码简单画图

    本文将介绍如何使用Python的海龟库进行简单画图,并提供相关示例代码。 一、基础用法 使用Python的海龟库,我们可以控制一个小海龟在窗口中移动,并利用它的“画笔”在窗口中绘制…

    编程 2025-04-29
  • Python樱花树代码简单

    本文将对Python樱花树代码进行详细的阐述和讲解,帮助读者更好地理解该代码的实现方法。 一、简介 樱花树是一种图形效果,它的实现方法比较简单。Python中可以通过turtle这…

    编程 2025-04-28
  • Python大神作品:让编程变得更加简单

    Python作为一种高级的解释性编程语言,一直被广泛地运用于各个领域,从Web开发、游戏开发到人工智能,Python都扮演着重要的角色。Python的代码简洁明了,易于阅读和维护,…

    编程 2025-04-28
  • 用Python实现简单爬虫程序

    在当今时代,互联网上的信息量是爆炸式增长的,其中很多信息可以被利用。对于数据分析、数据挖掘或者其他一些需要大量数据的任务,我们可以使用爬虫技术从各个网站获取需要的信息。而Pytho…

    编程 2025-04-28
  • 如何制作一个简单的换装游戏

    本文将从以下几个方面,为大家介绍如何制作一个简单的换装游戏: 1. 游戏需求和界面设计 2. 使用HTML、CSS和JavaScript开发游戏 3. 实现游戏的基本功能:拖拽交互…

    编程 2025-04-27
  • Guava Limiter——限流器的简单易用

    本文将从多个维度对Guava Limiter进行详细阐述,介绍其定义、使用方法、工作原理和案例应用等方面,并给出完整的代码示例,希望能够帮助读者更好地了解和使用该库。 一、定义 G…

    编程 2025-04-27
  • 制作一个简单的管理系统的成本及实现

    想要制作一个简单的管理系统,需要进行技术选型、开发、测试等过程,那么这个过程会花费多少钱呢?我们将从多个方面来阐述制作一个简单的管理系统的成本及实现。 一、技术选型 当我们开始思考…

    编程 2025-04-27
  • 2的32次方-1:一个看似简单却又复杂的数字

    对于计算机领域的人来说,2的32次方-1(也就是十进制下的4294967295)这个数字并不陌生。它经常被用来表示IPv4地址或者无符号32位整数的最大值。但实际上,这个数字却包含…

    编程 2025-04-27

发表回复

登录后才能评论