HttpPost向服务器传送数据

mac2024-07-20  55

首先获取token;

import org.springframework.stereotype.Component; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; @Component public class getToken { //,因为返回的字符串固定,粗暴的取出token数据 public String GetToken(){ String jsonData=ObjectUtils.toString(getURLContent()); System.out.println(jsonData); String[] split = jsonData.split("\""); if (!split[3].equals("ok")){ return null; } String token=split[9]; return token; } //向url拿带token的json字符串 public static String getURLContent() { String urlStr = "这里放拿token的url"; //请求的url URL url = null; //建立的http链接 HttpURLConnection httpConn = null; //请求的输入流 BufferedReader in = null; //输入流的缓冲 StringBuffer sb = new StringBuffer(); try{ url = new URL(urlStr); in = new BufferedReader(new InputStreamReader(url.openStream(),"UTF-8") ); String str = null; //一行一行进行读入 while((str = in.readLine()) != null) { sb.append( str ); } } catch (Exception ex) { System.out.println(ex.toString()); } finally{ try{ if(in!=null) { in.close(); //关闭流 } }catch(IOException ex) { System.out.println(ex.toString()); } } String result =sb.toString(); return result; } }

然后根据token向url传送数据

public void sendparklot() throws IOException { //获取token String token = ObjectUtils.toString(getToken.GetToken()); //parkDetails是我要想url传送的数据 JSONObject json = JSONObject.fromObject(parkDetails()); String data = json.toString(); //定义时间戳 Long Time = (DateTime.now().getMillis() / 1000); HttpPost httpPost = new HttpPost(“传送url的地址"); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build(); httpPost.setConfig(requestConfig); CloseableHttpClient httpClient = null; //设置传送数据Utf-8格式 StringEntity stringEntity = new StringEntity(data, HTTP.UTF_8); try { //设置头部信息 httpPost.setHeader("token", token); httpPost.setHeader("timestamp", Time.toString()); httpPost.setHeader("Content-Type", "application/json"); httpPost.addHeader("User-Agent", "imgfornote"); //加入传输的数据 httpPost.setEntity(stringEntity); /*设置post请求参数*/ httpClient = HttpClients.custom().disableAutomaticRetries().build(); HttpResponse response = httpClient.execute(httpPost); //这是url给你返回的信息 String content = EntityUtils.toString(response.getEntity()); return; } catch (Exception e) { } finally { if (httpPost != null){ httpPost.releaseConnection();} if (httpClient != null){ try { httpClient.close(); } catch (IOException e) { }} } }
最新回复(0)