用java语言编写一个简单的接口请求,get和post

2 篇文章 0 订阅
1 篇文章 0 订阅
package com.lyl.interfaces;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.testng.annotations.Test;
import org.apache.http.HttpResponse;
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.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

public class Demo {
	//日志
	private Logger logger=Logger.getLogger(Demo.class);
	@Test(enabled=false)
	public void testLoginPost() {
		//准备url
		String url = "http://******/api/member/login";
		//选择请求方式
		HttpPost httppost = new HttpPost(url);
		//准备参数
		List<BasicNameValuePair> para=new ArrayList<BasicNameValuePair>();
		BasicNameValuePair mobliePhone=	new BasicNameValuePair("mobilephone","**********");
		BasicNameValuePair pwd=new BasicNameValuePair("password", "e10adc3949ba59abbe56e057f20f883e");
		BasicNameValuePair type=new BasicNameValuePair("type", "1");
		para.add(mobliePhone);
		para.add(pwd);
		para.add(type);
		try {//把参数封装到请求体里面
			httppost.setEntity(new UrlEncodedFormEntity(para,"UTF-8"));
			//准备客户端
			HttpClient httpclient =HttpClients.createDefault();
			//发送请求,接受响应信息
		    HttpResponse respones=httpclient.execute(httppost);
		    //取出接口响应数据,并转成字符串
		    String result=  EntityUtils.toString(respones.getEntity());
		    System.out.println(result);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("post请求出问题啦");
		}
	}
	
	@Test
	public void testLoginGet(){
		        //准备url
				String url = "http://*******/api/member/login";
				//选择请求方式
				HttpGet httpget = new HttpGet(url);
				//准备参数
				List<BasicNameValuePair> para=new ArrayList<BasicNameValuePair>();
				BasicNameValuePair mobliePhone=	new BasicNameValuePair("mobilephone","*****");
				BasicNameValuePair pwd=new BasicNameValuePair("password", "e10adc3949ba59abbe56e057f20f883e");
				BasicNameValuePair type=new BasicNameValuePair("type", "1");
				para.add(mobliePhone);
				para.add(pwd);
				para.add(type);
				String paramers=URLEncodedUtils.format(para, "UTF-8");
				//将参数拼接在url上面
				url+=("?"+paramers);
				try {
					httpget.setURI(new URI(url));
					//准备客户端
					HttpClient httpclient=HttpClients.createDefault();
					//执行
			    	HttpResponse response=httpclient.execute(httpget);
			        String result=EntityUtils.toString(response.getEntity());
				} catch (Exception e) {
					// TODO Auto-generated catch block
					logger.error("get请求出问题啦");
				}
	}
}

好的,以下是一个使用 Java 语言编写的 HttpPost 请求示例: ``` import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; public class HttpPostExample { public static void main(String[] args) throws Exception { String url = "http://example.com/api"; Map<String, String> params = new HashMap<>(); params.put("username", "myusername"); params.put("password", "mypassword"); String response = sendHttpPost(url, params); System.out.println(response); } public static String sendHttpPost(String url, Map<String, String> params) throws IOException { URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); // add request header con.setRequestProperty("User-Agent", "Mozilla/5.0"); // generate url encoded parameters String urlParameters = getURLEncodedParameters(params); // Send post request con.setDoOutput(true); con.getOutputStream().write(urlParameters.getBytes("UTF-8")); int responseCode = con.getResponseCode(); System.out.println("Sending 'POST' request to URL : " + url); System.out.println("Post parameters : " + urlParameters); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); return response.toString(); } private static String getURLEncodedParameters(Map<String, String> params) throws UnsupportedEncodingException { StringBuilder result = new StringBuilder(); for (Map.Entry<String, String> entry : params.entrySet()) { result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); result.append("="); result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); result.append("&"); } return result.toString().substring(0, result.length() - 1); } } ``` 这段代码使用了 `java.net.HttpURLConnection` 类来发送 HTTP POST 请求,并将请求参数编码为 URL 编码形式。您可以根据需要修改 URL参数
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值