想了解如何使用Guzzle以JSON发送POST请求?的新动态吗?本文将为您提供详细的信息,我们还将为您解答关于givejson的相关问题,此外,我们还将为您介绍关于android–如何使用googl
想了解如何使用Guzzle以JSON发送POST请求?的新动态吗?本文将为您提供详细的信息,我们还将为您解答关于give json的相关问题,此外,我们还将为您介绍关于android – 如何使用google api客户端库为java发送带有JSON数据的POST请求?、ApiPost如何使用另一个接口的返回参数作为当前接口的Token发送Post请求、Java发送Post请求,参数JSON,接收JSON、json – 如何通过Swift发送POST请求?的新知识。
本文目录一览:- 如何使用Guzzle以JSON发送POST请求?(give json)
- android – 如何使用google api客户端库为java发送带有JSON数据的POST请求?
- ApiPost如何使用另一个接口的返回参数作为当前接口的Token发送Post请求
- Java发送Post请求,参数JSON,接收JSON
- json – 如何通过Swift发送POST请求?
如何使用Guzzle以JSON发送POST请求?(give json)
有人知道post
使用JSON 的正确方法Guzzle
吗?
$request = $this->client->post(self::URL_REGISTER,array( ''content-type'' => ''application/json'' ),array(json_encode($_POST)));
我internal server error
从服务器收到响应。它可以使用Chrome浏览器Postman
。
答案1
小编典典对于 Guzzle <= 4:
这是原始的发布请求,因此将JSON放入正文即可解决问题
$request = $this->client->post($url,array( ''content-type'' => ''application/json'' ),array());$request->setBody($data); #set body!$response = $request->send();return $response;
android – 如何使用google api客户端库为java发送带有JSON数据的POST请求?
这是我正在使用的片段
UrlEncodedContent urlEncodedContent = new UrlEncodedContent(paramMap); //paramMap contains email and password keypairs HttpRequest request = httpRequestFactory.buildPostRequest(new GenericUrl(Constants.PHP_SERVICE_BASE_PATH + mPath),urlEncodedContent); String response = request.execute().parseAsstring();
我没有得到预期的回应.我认为这是因为邮政参数,即电子邮件和密码没有以正确的格式发送.我需要用JSON发送它们.
注意:我没有将该库用于Google Web服务.
解决方法
Map<String,String> json = new HashMap<String,String>(); json.put("lat",Double.toString(location.getLatitude())); json.put("lng",Double.toString(location.getLongitude())); final HttpContent content = new JsonHttpContent(new JacksonFactory(),json); final HttpRequest request = getHttpRequestFactory().buildPostRequest(new GenericUrl(url),content);
ApiPost如何使用另一个接口的返回参数作为当前接口的Token发送Post请求
在实际生产环境中,我们常遇到一个问题,就是一个接口常常需要另一个接口的返回值作为请求参数。
比如,我们需要先通过一个接口A获取token,然后拿到这个token后作为第二个接口B的请求参数发送。
本文就来解决这个问题。
为了方便演示,我们先准备2个接口:A接口获取token,B接口使用token。
1、获取token的接口A
接口URL:[https://echo.apipost.cn/token.php](https://echo.apipost.cn/token.php)
content-type: application/json
,
请求Body参数:
{
"moible":1388888666,
"password":"123456"
}
返回示例:
{
"errcode":0,
"errstr":"success",
"token":"63fabf20700e17ac34d7f90d6d03caae"
}
2、使用token的接口B
接口URL:[https://echo.apipost.cn/echo.php](https://echo.apipost.cn/echo.php)
content-type: x-www-form-urlencoded
,
请求body参数:
{
"token":? // 需要从获取token接口拿到token作为请求参数
}
返回示例:
{
"errcode": 0,
"errstr": "success",
"post": [ // 提交的请求body参数
],
"header": {
"Host": "echo.apipost.cn",
"Connection": "keep-alive",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/78.0.3904.108 Safari\/537.36",
"Accept": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8,application\/signed-exchange;v=b3",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "zh-CN,zh;q=0.9",
"Cookie": "UM_distinctid=1709ee7b93f4-069ba9e2aa711c-2393f61-13c680-1709ee7b940389; PHPSESSID=oumoolom1338i8aafc6p3a1mhn; BAIDU_SSP_lcr=https:\/\/blog.csdn.net\/weixin_45316122\/article\/details\/95252977; Hm_lvt_a046ce178828e393614822a297b8d296=1588239504,1588239641,1588239650,1588252498; Hm_lpvt_a046ce178828e393614822a297b8d296=1588253907"
}
}
3、开始实现
准备
打开apipost,新建一个接口,URL直接填写 接口B的url:[http://echo.apipost.cn/echo.php](http://echo.apipost.cn/echo.php)
另外,我们定义一个变量{{token_var}}
放到请求body参数,如图
由于该变量{{token_var}}
并未被赋值,所以发送后,服务器端原样输出了{{token_var}}
,这不是我们想要的结果。
我们接下来通过2种方法对变量进行赋值。
实现方法一:
新建一个接口,请求参数和URL填写接口A的信息,如下图:
然后点击[后执行脚本
],输入以下脚本:
apt.variables.set("token_var", response.json.token);
这个脚本的意思是,把响应json的token赋给变量token_var
发送后,我们再去执行B接口,看到服务端已成功接收token,如下图:
实现方法二:
我们进接口B的“**预执行脚本**
”选项,选择[发送一个请求],然后改动请求示例为如下脚本:
apt.sendRequest({
"method":"post",
"url":"https://echo.apipost.cn/token.php",
"content-type":"application/json",
"data":JSON.stringify({
"mobile": 1388888666,
"password": "123456"
})
}, function (response) {
apt.variables.set("token_var", response.token);
});
这段脚本的意思是,向 [https://echo.apipost.cn/token.php](https://echo.apipost.cn/token.php)
发送一个 content-type
为application/json
的post请求,并且把返回结果的 token
赋给变量:token_var
如下图所示:
此时我们再点击发送,看到服务端已成功接收token,如下图:
参考文档:
ApiPost的预执行脚本和后执行脚本
ApiPost V3 如何设置一个变量?
Java发送Post请求,参数JSON,接收JSON
/**
* 发送post请求
* @param url 路径
* @param jsonObject 参数(json类型)
* @param encoding 编码格式
* @return
* @throws ParseException
* @throws IOException
*/
public static String send(String url, JSONObject jsonObject,String encoding) throws ParseException, IOException{
String body = "";
//创建httpclient对象
CloseableHttpClient client = HttpClients.createDefault();
//创建post方式请求对象
HttpPost httpPost = new HttpPost(url);
//装填参数
StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
//设置参数到请求对象中
httpPost.setEntity(s);
System.out.println("请求地址:"+url);
// System.out.println("请求参数:"+nvps.toString());
//设置header信息
//指定报文头【Content-type】、【User-Agent】
// httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//执行请求操作,并拿到结果(同步阻塞)
CloseableHttpResponse response = client.execute(httpPost);
//获取结果实体
HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, encoding);
}
EntityUtils.consume(entity);
//释放链接
response.close();
return body;
}
下面代码自己写。
2019/11/18,看到代码挺多人看的,再给大家提供一个Http工具类,数据提交包括 Raw,Json等
package com.xiaojiang.checkin.utils;
import com.alibaba.fastjson.JSONObject;
import com.xiaojiang.checkin.entity.HttpClientResult;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.*;
/**
* Description: httpClient工具类
*
* @author JourWon
* @date Created on 2018年4月19日
*/
public class HttpClientUtils {
// 编码格式。发送编码格式统一用UTF-8
private static final String ENCODING = "UTF-8";
// 设置连接超时时间,单位毫秒。
private static final int CONNECT_TIMEOUT = 6000;
// 请求获取数据的超时时间(即响应时间),单位毫秒。
private static final int SOCKET_TIMEOUT = 6000;
/**
* 发送get请求;不带请求头和请求参数
*
* @param url 请求地址
* @return
* @throws Exception
*/
public static HttpClientResult doGet(String url) throws Exception {
return doGet(url, null, null);
}
/**
* 发送get请求;带请求参数
*
* @param url 请求地址
* @param params 请求参数集合
* @return
* @throws Exception
*/
public static HttpClientResult doGet(String url, Map<String, String> params) throws Exception {
return doGet(url, null, params);
}
/**
* 发送get请求;带请求头和请求参数
*
* @param url 请求地址
* @param headers 请求头集合
* @param params 请求参数集合
* @return
* @throws Exception
*/
public static HttpClientResult doGet(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
// 创建httpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建访问的地址
URIBuilder uriBuilder = new URIBuilder(url);
if (params != null) {
Set<Map.Entry<String, String>> entrySet = params.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
uriBuilder.setParameter(entry.getKey(), entry.getValue());
}
}
// 创建http对象
HttpGet httpGet = new HttpGet(uriBuilder.build());
/**
* setConnectTimeout:设置连接超时时间,单位毫秒。
* setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection
* 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
* setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
*/
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpGet.setConfig(requestConfig);
// 设置请求头
packageHeader(headers, httpGet);
// 创建httpResponse对象
CloseableHttpResponse httpResponse = null;
try {
// 执行请求并获得响应结果
return getHttpClientResult(httpResponse, httpClient, httpGet);
} finally {
// 释放资源
release(httpResponse, httpClient);
}
}
/**
* 发送post请求;不带请求头和请求参数
*
* @param url 请求地址
* @return
* @throws Exception
*/
public static HttpClientResult doPost(String url) throws Exception {
return doPost(url, null, null);
}
/**
* 发送post请求;带请求参数
*
* @param url 请求地址
* @param params 参数集合
* @return
* @throws Exception
*/
public static HttpClientResult doPost(String url, Map<String, String> params) throws Exception {
return doPost(url, null, params);
}
/**
* 发送post请求;带请求头和请求参数
*可发送Formdata数据,请把请求头设置一下,不然获取不到数据。
* @param url 请求地址
* @param headers 请求头集合
* @param params 请求参数集合
* @return
* @throws Exception
*/
public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
// 创建httpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建http对象
HttpPost httpPost = new HttpPost(url);
/**
* setConnectTimeout:设置连接超时时间,单位毫秒。
* setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection
* 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
* setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
*/
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpPost.setConfig(requestConfig);
// 设置请求头
/*httpPost.setHeader("Cookie", "");
httpPost.setHeader("Connection", "keep-alive");
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");*/
packageHeader(headers, httpPost);
// 封装请求参数
packageParam(params, httpPost);
// 创建httpResponse对象
CloseableHttpResponse httpResponse = null;
try {
// 执行请求并获得响应结果
return getHttpClientResult(httpResponse, httpClient, httpPost);
} finally {
// 释放资源
release(httpResponse, httpClient);
}
}
/***
* 发送post请求封装formdata
*
*/
// public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params){
//
// }
/**
* 发送POST请求带Raw参数
* */
public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params,String raw) throws Exception {
// 创建httpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建http对象
HttpPost httpPost = new HttpPost(url);
//封装raw 参数
packageRaw(raw,httpPost);
/**
* setConnectTimeout:设置连接超时时间,单位毫秒。
* setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection
* 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
* setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
*/
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpPost.setConfig(requestConfig);
// 设置请求头
/*httpPost.setHeader("Cookie", "");
httpPost.setHeader("Connection", "keep-alive");
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");*/
packageHeader(headers, httpPost);
// 封装请求参数
packageParam(params, httpPost);
// 创建httpResponse对象
CloseableHttpResponse httpResponse = null;
try {
// 执行请求并获得响应结果
return getHttpClientResult(httpResponse, httpClient, httpPost);
} finally {
// 释放资源
release(httpResponse, httpClient);
}
}
/***
* 发送Post有些这封装代码
* 封装formdata数据
*/
public static void packageFormData(Map<String,String> params,HttpEntityEnclosingRequestBase HttpMethod){
List<NameValuePair> paramList = new ArrayList <NameValuePair>();
if(params != null && params.size() > 0){
Set<String> keySet = params.keySet();
for(String key : keySet) {
paramList.add(new BasicNameValuePair(key, params.get(key)));
}
}
HttpMethod.setEntity(new UrlEncodedFormEntity(paramList,Charset.forName("UTF-8")));
System.out.println(paramList);
}
/**
* 封装Raw数据
* */
public static void packageRaw(String raw,HttpEntityEnclosingRequestBase HttpMethod){
try {
//传map进来需要自己封装key,val
StringEntity postingString = new StringEntity(raw);// json传递
HttpMethod.setEntity(postingString);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
/**
* 发送put请求;不带请求参数
*
* @param url 请求地址
* @return
* @throws Exception
*/
public static HttpClientResult doPut(String url) throws Exception {
return doPut(url);
}
/**
* 发送put请求;带请求参数
*
* @param url 请求地址
* @param params 参数集合
* @return
* @throws Exception
*/
public static HttpClientResult doPut(String url, Map<String, String> params) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPut httpPut = new HttpPut(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpPut.setConfig(requestConfig);
packageParam(params, httpPut);
CloseableHttpResponse httpResponse = null;
try {
return getHttpClientResult(httpResponse, httpClient, httpPut);
} finally {
release(httpResponse, httpClient);
}
}
/**
* 发送delete请求;不带请求参数
*
* @param url 请求地址
* @return
* @throws Exception
*/
public static HttpClientResult doDelete(String url) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpDelete httpDelete = new HttpDelete(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpDelete.setConfig(requestConfig);
CloseableHttpResponse httpResponse = null;
try {
return getHttpClientResult(httpResponse, httpClient, httpDelete);
} finally {
release(httpResponse, httpClient);
}
}
/**
* 发送delete请求;带请求参数
*
* @param url 请求地址
* @param params 参数集合
* @return
* @throws Exception
*/
public static HttpClientResult doDelete(String url, Map<String, String> params) throws Exception {
if (params == null) {
params = new HashMap<String, String>();
}
params.put("_method", "delete");
return doPost(url, params);
}
/**
* Description: 封装请求头
* @param params
* @param httpMethod
*/
public static void packageHeader(Map<String, String> params, HttpRequestBase httpMethod) {
// 封装请求头
if (params != null) {
Set<Map.Entry<String, String>> entrySet = params.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
// 设置到请求头到HttpRequestBase对象中
httpMethod.setHeader(entry.getKey(), entry.getValue());
}
}
}
/**
* Description: 封装请求参数
*
* @param params
* @param httpMethod
* @throws UnsupportedEncodingException
*/
public static void packageParam(Map<String, String> params, HttpEntityEnclosingRequestBase httpMethod)
throws UnsupportedEncodingException {
// 封装请求参数
if (params != null) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Set<Map.Entry<String, String>> entrySet = params.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
// 设置到请求的http对象中
httpMethod.setEntity(new UrlEncodedFormEntity(nvps, ENCODING));
}
}
/**
* Description: 获得响应结果
*
* @param httpResponse
* @param httpClient
* @param httpMethod
* @return
* @throws Exception
*/
public static HttpClientResult getHttpClientResult(CloseableHttpResponse httpResponse,
CloseableHttpClient httpClient, HttpRequestBase httpMethod) throws Exception {
// 执行请求
httpResponse = httpClient.execute(httpMethod);
// 获取返回结果
if (httpResponse != null && httpResponse.getStatusLine() != null) {
String content = "";
if (httpResponse.getEntity() != null) {
content = EntityUtils.toString(httpResponse.getEntity(), ENCODING);
}
return new HttpClientResult(httpResponse.getStatusLine().getStatusCode(),content);
}
return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
/**
* Description: 释放资源
*
* @param httpResponse
* @param httpClient
* @throws IOException
*/
public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {
// 释放资源
if (httpResponse != null) {
httpResponse.close();
}
if (httpClient != null) {
httpClient.close();
}
}
}
json – 如何通过Swift发送POST请求?
def create if (@user = User.find_by_email(params[:email])) && @user.valid_password?(params[:password]) render json: @user.as_json(only: [:email,:authentication_token]),status: :created else render json:('Unauthorized Access') end end
当我使用Postman发出此请求时,我选择Body,并形成数据并添加电子邮件和密码.这个工作
如何使用swift做同样的事情?这就是我的尝试
let url = URL(string: "http://localhost:3000/api/v1/user_serialized/") let config = URLSessionConfiguration.default let request = NSMutableuRLRequest(url: url!) request.httpMethod = "POST" let bodyData = "email=Test@test.com&password=Test1234" request.httpBody = bodyData.data(using: String.Encoding.utf8); let session = URLSession(configuration: config) let task = session.dataTask(with: url! as URL,completionHandler: {(data,response,error) in let json = JSON(data:data!) debugPrint(json) }) task.resume()
解决方法
这是我的代码的样子:
private let url = URL(string: "http://example.com/")! func httpPost(jsonData: Data) { if !jsonData.isEmpty { var request = URLRequest(url: url) request.httpMethod = "POST" request.httpBody = jsonData URLSession.shared.getAllTasks { (openTasks: [URLSessionTask]) in NSLog("open tasks: \(openTasks)") } let task = URLSession.shared.dataTask(with: request,completionHandler: { (responseData: Data?,response: URLResponse?,error: Error?) in NSLog("\(response)") }) task.resume() } }
今天的关于如何使用Guzzle以JSON发送POST请求?和give json的分享已经结束,谢谢您的关注,如果想了解更多关于android – 如何使用google api客户端库为java发送带有JSON数据的POST请求?、ApiPost如何使用另一个接口的返回参数作为当前接口的Token发送Post请求、Java发送Post请求,参数JSON,接收JSON、json – 如何通过Swift发送POST请求?的相关知识,请在本站进行查询。
本文标签: