如何将服务器返回的token信息保存到config下?

package com.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import net.sf.json.JSONObject;

public class Login {
	private static final String userName=FileUtils.readPropertiesFile("zhUserName", Constant.FILE_NAME, true);
	private static final String password=FileUtils.readPropertiesFile("zhPwd", Constant.FILE_NAME, true);
	private static final String url=FileUtils.readPropertiesFile("testUrl", Constant.FILE_NAME, true);
	private static final Logger log = Logger.getLogger(Login.class);
	
	
	public String getToken(){
		CloseableHttpClient httpClient=HttpClients.createDefault();
		HttpPost httpPost=new HttpPost(url+"/open_api/auth/partner_token/");
		httpPost.setHeader("Accept", "application/json");
		httpPost.setHeader("Content-Type", "application/json");
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("identity", userName);
		jsonObject.put("password", password);
	
		StringEntity stringEntity=new StringEntity(jsonObject.toString(), "utf-8");
		httpPost.setEntity(stringEntity);
		CloseableHttpResponse response=null;
		String jsonString="";
		String result="";
		
		try {
			response=httpClient.execute(httpPost);
			StatusLine statusLine=response.getStatusLine();
			if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity responseEntity = response.getEntity();
				jsonString = EntityUtils.toString(responseEntity);
				log.info("return data: " + jsonString);
			} else {
				log.error("error message:" + EntityUtils.toString(response.getEntity()));
			}
				
		} catch (IOException e) {
			e.printStackTrace();
			log.error("happan an error when POST data: " + e.getMessage());
		}finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			try {
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(jsonObject!=null){
			JSONObject json=JSONObject.fromObject(jsonString);
			result=json.get("token").toString();
			//修改config中得token
			InputStream inputStream=null;
			OutputStream outputStream=null;
			try {
				inputStream=new FileInputStream(new File(Thread.currentThread().getContextClassLoader()
						.getResource("config.properties").getFile()));
				Properties properties=new Properties();
				properties.load(inputStream);				
				properties.setProperty("token", result);
				
				outputStream=new FileOutputStream(new File(Thread.currentThread().getContextClassLoader()
						.getResource("config.properties").getFile())); 
				properties.store(outputStream, "");
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally {
				try {
					inputStream.close();
					outputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
		}
		
		return result;
		
	}

	public static void main(String[] args) {
	
		Login login=new Login();
		System.out.println(login.getToken());
		
		String token=FileUtils.readPropertiesFile("token", Constant.FILE_NAME, true);
		System.out.println(token);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Python 中,可以使用 JSON Web Token (JWT) 来保存用户信息。JWT 是一种安全的身份验证机制,可以将用户信息编码为一个 token,并在用户登录后将该 token 发送给客户端保存,客户端在每次请求时将该 token 发送给服务器验证用户身份。 以下是使用 Flask 和 JWT 实现用户身份验证的示例代码: ```python from flask import Flask, jsonify, request import jwt app = Flask(__name__) app.config['SECRET_KEY'] = 'secret_key' # 用户登录 @app.route('/login', methods=['POST']) def login(): # 获取用户名和密码 username = request.json.get('username', None) password = request.json.get('password', None) # 验证用户名和密码 if username == 'admin' and password == 'password': # 生成 token token = jwt.encode({'username': username}, app.config['SECRET_KEY']) return jsonify({'token': token.decode('utf-8')}) else: return jsonify({'error': '用户名或密码错误'}) # 需要身份验证的 API @app.route('/api', methods=['GET']) def api(): # 获取 token token = request.headers.get('Authorization', None) if not token: return jsonify({'error': '未提供 token'}) # 验证 token try: data = jwt.decode(token, app.config['SECRET_KEY']) return jsonify({'username': data['username']}) except: return jsonify({'error': '无效的 token'}) if __name__ == '__main__': app.run() ``` 在该示例中,用户登录后会生成一个包含用户名信息token,并将其返回给客户端。客户端在每次请求需要身份验证的 API 时都需要将该 token 发送给服务器进行验证。如果 token 验证成功,则返回包含用户名的 JSON 数据,否则返回错误信息
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值