测试京东万象的Webservice接口

版权声明:本篇文章由IT_CREATE整理 https://blog.csdn.net/IT_CREATE/article/details/86600858

代码:

package com.ge.webservicetest.restfultest;

import java.io.IOException;
import javax.ws.rs.core.Response;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.junit.Test;

public class HttpClientTest {
	/**
	 * 测试京东万象  ---- 笑话接口
	 */
	@Test
	public void showapi() {
		PostMethod post = new PostMethod("https://way.jd.com/showapi/dtgxt");
		//封装请求参数
		NameValuePair param01 = new NameValuePair("page", "1");
		NameValuePair param02 = new NameValuePair("maxResult", "10");
		NameValuePair param03 = new NameValuePair("appkey", "自己的appkey");
		post.setRequestBody(new NameValuePair[] {param01,param02,param03});	
		handleHttpMethod(post);//执行POST请求	
		try {	
			//获得POST方法,返回的结果
			System.out.println(post.getResponseBodyAsString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
	/**
	 * 测试京东万象  ---- 菜谱接口
	 */
	@Test
	public void jisuapi() {
		/**
		 * 模拟GET请求的发送
		 */
		GetMethod get = new GetMethod("https://way.jd.com/jisuapi/search");
		//封装请求参数
		NameValuePair param01 = new NameValuePair("keyword", "土豆");
		NameValuePair param02 = new NameValuePair("num", "10");
		NameValuePair param03 = new NameValuePair("appkey", "自己的appkey");
		get.setQueryString(new NameValuePair[] {param01,param02,param03});
		handleHttpMethod(get);//执行GET请求
		try {		
			//获得GET方法,返回的结果
			System.out.println(get.getResponseBodyAsString());
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	private void handleHttpMethod(HttpMethod method) {
		// TODO Auto-generated method stub
		HttpClient client = new HttpClient();
		int statusCode = 0;
		
		try {
			//执行HTTP方法,并返回响应码
			statusCode = client.executeMethod(method);
			
			//根据返回的状态码,转换对应的状态枚举
			Response.Status status = Response.Status.fromStatusCode(statusCode);
			if(status == Response.Status.OK) {
				System.out.println("后台处理完毕!");
			}else if(status == Response.Status.NOT_FOUND) {
				System.out.println("请求路径错误!");
			}else if(status == Response.Status.METHOD_NOT_ALLOWED) {
				System.out.println("请求方法不被允许!");
			}	
//			……
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}	
}

猜你喜欢

转载自blog.csdn.net/IT_CREATE/article/details/86600858