I have developed a password verification system using Arduino Nano+ESP8266 (FrontEnd) and Backend with Flask REST API server.
Following is my code of ESP8266, Which is passing the HTTP POST request to REST API server,
#include <ESP8266WiFi.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <ESP8266HTTPClient.h>
#include<SoftwareSerial.h>
SoftwareSerial link(4, 0);
byte greenLED = 13;
byte statusLED = 14;
String hexstring = "";
// Replace with your network credentials
const char *ssid = "***********";
const char *password = "***********";
const long utcOffsetInSeconds = 240;
// Define NTP Client to get time
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "asia.pool.ntp.org", utcOffsetInSeconds);
//Week Days
String weekDays[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
//Month names
String months[12] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
void setup() {
// Initialize Serial Monitor
Serial.begin(115200);
Serial.print("Initializing System");
for (int i = 10; i > 0; i--) {
delay(500);
Serial.print(i); Serial.println(' ');
}
pinMode(statusLED, OUTPUT);
// Connect to Wi-Fi
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
link.begin(9600);
link.setTimeout(100);
// clear any pending stuff
link.readString();
pinMode(greenLED, OUTPUT);
}
// Initialize a NTPClient to get time
timeClient.begin();
timeClient.setTimeOffset(19770);
}
void loop() {
timeClient.update();
unsigned long epochTime = timeClient.getEpochTime();
String formattedTime = timeClient.getFormattedTime();
int currentHour = timeClient.getHours();
int currentMinute = timeClient.getMinutes();
int currentSecond = timeClient.getSeconds();
String weekDay = weekDays[timeClient.getDay()];
//Get a time structure
struct tm *ptm = gmtime ((time_t *)&epochTime);
int monthDay = ptm->tm_mday;
int currentMonth = ptm->tm_mon + 1;
String currentMonthName = months[currentMonth - 1];
int currentYear = ptm->tm_year + 1900;
//Print complete date:
String currentDate = String(currentYear) + String(currentMonth) + String(monthDay) + String(currentHour) + String(currentMinute) + String(currentSecond);
delay(1000);
if (link.available()) {
String rec = link.readString();
Serial.print(F("rec:")); Serial.println(rec);
if (rec.length() > 0) { // print it out
Serial.println(F("Received data"));
for (size_t i = 0; i < rec.length(); i++) {
digitalWrite(greenLED, HIGH); //flash led to show data is arriving
delay(20);
digitalWrite(greenLED, LOW);
if (i % 8 == 0) {
Serial.println();
}
Serial.print(" 0x");
if (rec[i] < 10) {
Serial.print("0");
hexstring += '0';
}
Serial.print(rec[i], HEX);
hexstring += String(rec[i], HEX);
}
Serial.println();
Serial.print("Current Date: ");
Serial.println(currentDate);
Serial.println("Your String Sir:");
Serial.print(hexstring);
Serial.println();
//confirmation();
String sub1 = hexstring.substring(0, 2);
String sub2 = hexstring.substring(16, 32);
String sub3 = hexstring.substring(32, 34);
if (sub3 == "31") { //New User Registartion
String data = "{\"user_id\" :\"" + sub1 + "\",\"encrypted_password\" :\"" + sub2 + "\",\"option\" :\"" + sub3 + "\" ,\"request_datetime\" :\"" + currentDate + "\"}";
HTTPClient http; //Declare object of class HTTPClient
http.begin("http://192.168.8.228:5000/users/"); //Specify request destination
http.addHeader("Content-Type", "application/json");
int httpCode = http.POST(data.c_str());
if (httpCode == 200) {
String payload = http.getString(); //Get the response payload
Serial.println(httpCode); //Print HTTP return code
Serial.println(payload); //Print request response payload
if (payload == "Code1") {
link.read();
Serial.println(F("Prompt other side Confirmation"));
link.print("Success_Code1");
digitalWrite(statusLED, HIGH); //flash led to show data is arriving
delay(20);
digitalWrite(statusLED, LOW);
}
else {
link.read();
Serial.println(F("Prompt other side Error1"));
link.print("Error 1");
}
}
http.end();
rec = ""; // clear for next receive
hexstring = ""; //Clear hexstring
}
else if (sub3 == "32") { //Confirm Password
String data ="{\"user_id\":\"" + sub1 + "\",\"encrypted_password\":\"" + sub2 + "\",\"option\":\"" + sub3 + "\" ,\"request_datetime\":\"" + currentDate + "\"}";
HTTPClient http; //Declare object of class HTTPClient
String link2 = "http://192.168.8.228:5000/users/" + sub1;
http.begin(link2); //Specify request destination
http.addHeader("Content - Type", "application / json");
int httpCode = http.POST(data.c_str());
delay(1000);
Serial.println(data.c_str());
Serial.println(httpCode);
if (httpCode == 200) {
String payload = http.getString(); //Get the response payload
Serial.println(httpCode); //Print HTTP return code
Serial.println(payload); //Print request response payload
if (payload == "Code2") {
link.read();
Serial.println(F("Prompt other side Confirmation"));
link.print("Success_Code1");
digitalWrite(statusLED, HIGH); //flash led to show data is arriving
delay(20);
digitalWrite(statusLED, LOW);
}
}
else {
link.read();
Serial.println(F("Prompt other side Error1"));
link.print("Error 1");
}
http.end();
rec = ""; // clear for next receive
hexstring = ""; //Clear hexstring
}
else if (sub3 == "33") { //Change Password
String data = "{\"user_id\" :\"" + sub1 + "\",\"encrypted_password\" :\"" + sub2 + "\",\"option\" :\"" + sub3 + "\" ,\"request_datetime\" :\"" + currentDate + "\"}";
HTTPClient http; //Declare object of class HTTPClient
http.begin("http://192.168.8.228:5000/users/"); //Specify request destination
http.addHeader("Content-Type", "application/json");
int httpCode = http.POST(data.c_str());
if (httpCode == 200) {
String payload = http.getString(); //Get the response payload
Serial.println(httpCode); //Print HTTP return code
Serial.println(payload); //Print request response payload
if (payload == "Code3") {
link.read();
Serial.println(F("Prompt other side Confirmation"));
link.print("Success_Code1");
digitalWrite(statusLED, HIGH); //flash led to show data is arriving
delay(20);
digitalWrite(statusLED, LOW);
}
}
else {
link.read();
Serial.println(F("Prompt other side Error1"));
link.print("Error 1");
}
http.end();
rec = ""; // clear for next receive
hexstring = ""; //Clear hexstring
}
}
}
}
As you can see, There are 3 methods,
New user registration code part:
if (sub3 == "31") { //New User Registartion
String data = "{\"user_id\" :\"" + sub1 + "\",\"encrypted_password\" :\"" + sub2 + "\",\"option\" :\"" + sub3 + "\" ,\"request_datetime\" :\"" + currentDate + "\"}";
HTTPClient http; //Declare object of class HTTPClient
http.begin("http://192.168.8.228:5000/users/"); //Specify request destination
http.addHeader("Content-Type", "application/json");
int httpCode = http.POST(data.c_str());
if (httpCode == 200) {
String payload = http.getString(); //Get the response payload
Serial.println(httpCode); //Print HTTP return code
Serial.println(payload); //Print request response payload
if (payload == "Code1") {
link.read();
Serial.println(F("Prompt other side Confirmation"));
link.print("Success_Code1");
digitalWrite(statusLED, HIGH); //flash led to show data is arriving
delay(20);
digitalWrite(statusLED, LOW);
}
else {
link.read();
Serial.println(F("Prompt other side Error1"));
link.print("Error 1");
}
}
http.end();
rec = ""; // clear for next receive
hexstring = ""; //Clear hexstring
}
Verify password code part:
else if (sub3 == "32") { //Confirm Password
String data ="{\"user_id\":\"" + sub1 + "\",\"encrypted_password\":\"" + sub2 + "\",\"option\":\"" + sub3 + "\" ,\"request_datetime\":\"" + currentDate + "\"}";
HTTPClient http; //Declare object of class HTTPClient
String link2 = "http://192.168.8.228:5000/users/" + sub1;
http.begin(link2); //Specify request destination
http.addHeader("Content - Type", "application / json");
int httpCode = http.POST(data.c_str());
delay(1000);
Serial.println(data.c_str());
Serial.println(httpCode);
if (httpCode == 200) {
String payload = http.getString(); //Get the response payload
Serial.println(httpCode); //Print HTTP return code
Serial.println(payload); //Print request response payload
if (payload == "Code2") {
link.read();
Serial.println(F("Prompt other side Confirmation"));
link.print("Success_Code1");
digitalWrite(statusLED, HIGH); //flash led to show data is arriving
delay(20);
digitalWrite(statusLED, LOW);
}
}
else {
link.read();
Serial.println(F("Prompt other side Error1"));
link.print("Error 1");
}
http.end();
rec = ""; // clear for next receive
hexstring = ""; //Clear hexstring
}
Below is my Flask/Python API server backend code:
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
import uuid
app = Flask(__name__)
db = SQLAlchemy(app)
DEBUG = True
# app.config['SECRET_KEY'] = 'secret'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root#localhost:3306/app'
print("App2 Change2")
class User(db.Model):
id = db.Column(db.Integer, primary_key=True, index=True)
user_id = db.Column(db.VARCHAR(10), nullable=False, unique=True)
encrypted_password = db.Column(db.VARCHAR(20), nullable=False)
option = db.Column(db.VARCHAR(3), nullable=False)
request_datetime = db.Column(db.VARCHAR(20), nullable=False)
public_id = db.Column(db.VARCHAR(100), nullable=False)
def __repr__(self):
return f'User <{self.public_id}>'
db.create_all()
#app.route('/')
def home():
return {
'message': 'Welcome to Vinod Test App'
}
#app.route('/users/')
def get_users():
return jsonify([
{
'user_id': user.user_id, 'encrypted_password': user.encrypted_password, 'option': user.option,
'request_datetime': user.request_datetime
} for user in User.query.all()
])
#app.route('/users/<user_id>/')
def get_user(user_id):
print(user_id)
user = User.query.filter_by(user_id=user_id).first_or_404()
return {
'user_id': user.user_id, 'encrypted_password': user.encrypted_password,
'public_id': user.public_id, 'original_time': user.request_datetime
}
# Add New User
#app.route('/users/', methods=['POST'])
def create_user():
data = request.get_json()
print(request.get_json())
if not 'user_id' in data or not 'encrypted_password' in data or not 'option' in data:
return jsonify({
'error': 'Bad Request',
'message': 'User Id and Encrypted Data is Missing'
}), 400
if len(data['encrypted_password']) < 16:
return jsonify({
'error': 'Bad Request',
'message': 'Length Error in Encrypted Data'
}), 400
u = User(
user_id=data['user_id'],
encrypted_password=data['encrypted_password'],
option=data.get('option'),
request_datetime=data['request_datetime'],
public_id=str(uuid.uuid4())
)
db.session.add(u)
db.session.commit()
return {
'id': u.user_id, 'encrypted_data': u.encrypted_password,
'public_id': u.public_id, 'original_time': u.request_datetime,
}, 200
# Verify Password
#app.route('/users/<user_id>', methods=['POST'])
def check_user(user_id):
data = request.get_json()
if 'user_id' not in data:
return {
'error': 'Bad Request',
'message': 'User_id field needs to be present'
}, 400
user = User.query.filter_by(user_id=user_id).first_or_404()
user.user_id = data['user_id']
if 'user_id' in data:
if user.encrypted_password == data['encrypted_password']:
return jsonify({
'user_id': user.public_id,
'encrypted_password': user.encrypted_password,
'original_time': user.request_datetime
})
else:
return {
'error': 'Bad Request',
'message': 'Password Do Not Match'
}, 400
#app.route('/users/<user_id>/', methods=['DELETE'])
def delete_user(user_id):
user = User.query.filter_by(user_id=user_id).first_or_404()
db.session.delete(user)
db.session.commit()
return {
'success': 'Data deleted successfully'
}
if __name__ == '__main__':
app.run(debug=True)
My issue is: It is not working when verify password passed through the ESP8266 to the Backend for verify password. But new user registration works when passed through ESP8266.
Below is the error I am getting in the PyCharm:
* Running on http://192.168.8.100:5000/ (Press CTRL+C to quit)
[2021-09-26 14:57:55,237] ERROR in app: Exception on /users/32 [POST]
Traceback (most recent call last):
File "C:\Users\Vinod Amarathunga\PycharmProject\Test1\server1\venv\lib\site-packages\flask\app.py", line 2070, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\Vinod Amarathunga\PycharmProject\Test1\server1\venv\lib\site-packages\flask\app.py", line 1515, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\Vinod Amarathunga\PycharmProject\Test1\server1\venv\lib\site-packages\flask\app.py", line 1513, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\Vinod Amarathunga\PycharmProject\Test1\server1\venv\lib\site-packages\flask\app.py", line 1499, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "C:\Users\Vinod Amarathunga\PycharmProject\Test1\server1\app2_Change2.py", line 108, in check_user
if 'user_id' not in data:
TypeError: argument of type 'NoneType' is not iterable
192.168.8.174 - - [26/Sep/2021 15:52:20] "POST /users/32 HTTP/1.1" 500 -
But when I send the same request (Verify Password) from Postman it works,
Below is the Postman response on verification:
This request was the same sent from ESP8266 which was captured from Mockon test server:
Backend expected response [Working with Postman]
192.168.8.103 - - [26/Sep/2021 15:52:59] "POST /users/32 HTTP/1.1" 400 -
Note: Encrypted data along with user inputs are passed to ESP by an Arduino Nano as below:
The error TypeError: argument of type 'NoneType' is not iterable means that your data = request.get_json() return a None. The reason why it return a None can be found in falsk.Request.get_json API documentation. It said:
By default this function will return None if the mimetype is not application/json
Take a look at your Arduino code, you add extra spaces on the http header:
http.addHeader("Content - Type", "application / json");
The HTTP header should be:
Content-Type: application/json
Related
My RFID wont read any card. The Rfid card is on with red led at D1. I do not know what is the problem though. Below is my code. Please assist
The picture is connection between the rfid and esp8266
//*******************************libraries********************************
//RFID-----------------------------
#include <SPI.h>
#include <MFRC522.h>
//NodeMCU--------------------------
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
//************************************************************************
#define SS_PIN D2 //D2
#define RST_PIN D1 //D1
//************************************************************************
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
//************************************************************************
/* Set these to your desired credentials. */
const char *ssid = "***";
const char *password = "***";
const char* device_token = " 4876407e7cbc0c2b";
//************************************************************************
String URL = "http://192.168.0.110/rfidattendance/getdata.php"; //computer IP or the server domain
String getData, Link;
String OldCardID = "";
unsigned long previousMillis = 0;
//************************************************************************
void setup() {
delay(1000);
Serial.begin(115200);
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522 card
//---------------------------------------------
connectToWiFi();
}
//************************************************************************
void loop() {
//check if there's a connection to Wi-Fi or not
if(!WiFi.isConnected()){
connectToWiFi(); //Retry to connect to Wi-Fi
}
//---------------------------------------------
if (millis() - previousMillis >= 15000) {
previousMillis = millis();
OldCardID="";
}
delay(50);
//---------------------------------------------
//look for new card
if ( ! mfrc522.PICC_IsNewCardPresent()) {
return;//got to start of loop if there is no card present
}
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial()) {
return;//if read card serial(0) returns 1, the uid struct contians the ID of the read card.
}
String CardID ="";
for (byte i = 0; i < mfrc522.uid.size; i++) {
CardID += mfrc522.uid.uidByte[i];
}
//---------------------------------------------
if( CardID == OldCardID ){
return;
}
else{
OldCardID = CardID;
}
//---------------------------------------------
// Serial.println(CardID);
SendCardID(CardID);
delay(1000);
}
//************send the Card UID to the website*************
void SendCardID( String Card_uid ){
Serial.println("Sending the Card ID");
if(WiFi.isConnected()){
HTTPClient http; //Declare object of class HTTPClient
//GET Data
getData = "?card_uid=" + String(Card_uid) + "&device_token=" + String(device_token); // Add the Card ID to the GET array in order to send it
//GET methode
Link = URL + getData;
// http.begin(Link); //initiate HTTP request //Specify content-type header
int httpCode = http.GET(); //Send the request
String payload = http.getString(); //Get the response payload
// Serial.println(Link); //Print HTTP return code
Serial.println(httpCode); //Print HTTP return code
Serial.println(Card_uid); //Print Card ID
Serial.println(payload); //Print request response payload
if (httpCode == 200) {
if (payload.substring(0, 5) == "login") {
String user_name = payload.substring(5);
// Serial.println(user_name);
}
else if (payload.substring(0, 6) == "logout") {
String user_name = payload.substring(6);
// Serial.println(user_name);
}
else if (payload == "succesful") {
}
else if (payload == "available") {
}
delay(100);
http.end(); //Close connection
}
}
}
//********************connect to the WiFi******************
void connectToWiFi(){
WiFi.mode(WIFI_OFF); //Prevents reconnection issue (taking too long to connect)
delay(1000);
WiFi.mode(WIFI_STA);
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP()); //IP address assigned to your ESP
delay(1000);
}
//=======================================================================
When I execute it, the rfid scanner is turn on but it does not read any card. I am using MFRC522, The wifi is connected successfully. I already pin the connection correctly
I understand that sending a transaction proposal (like the code below)
return channel.sendTransactionProposal(request);
}).then((proposalResponse) => {
//need to decode results
});
in which proposalResponse is a ProposalResponseObject (https://fabric-sdk-node.github.io/global.html#ProposalResponseObject__anchor) in which ProposalResponseObject[0] is an array of ProposalResponse.
I too understand that
proposalResponse[0][i].response.payload is the return message of shim.Success
But how to I decode proposalResponse[0][i].payload and proposalResponse[1]?
I tried to take a look at BlockDecoder (https://github.com/hyperledger/fabric-sdk-node/blob/release-1.1/fabric-client/lib/BlockDecoder.js) but I can't find the correct method to decode the aforementioned items?
I looked into protobuf structure of the payload response and used codes in the BlockDecoder.js. In case anybody is interested:
var grpc = require('grpc');
var _responseProto = grpc.load(__dirname + '/node_modules/fabric-client/lib/protos/peer/proposal_response.proto').protos;
var _proposalProto = grpc.load(__dirname + '/node_modules/fabric-client/lib/protos/peer/proposal.proto').protos;
var _rwsetProto = grpc.load(__dirname + '/node_modules/fabric-client/lib/protos/ledger/rwset/rwset.proto').rwset;
var _kv_rwsetProto = grpc.load(__dirname + '/node_modules/fabric-client/lib/protos/ledger/rwset/kvrwset/kv_rwset.proto').kvrwset;
var _ccEventProto = grpc.load(__dirname + '/node_modules/fabric-client/lib/protos/peer/chaincode_event.proto').protos;
module.exports = function decodeProposalResponsePayload(proposal_response_payload_bytes) {
var proposal_response_payload = {};
var proto_proposal_response_payload = _responseProto.ProposalResponsePayload.decode(proposal_response_payload_bytes);
proposal_response_payload.proposal_hash = proto_proposal_response_payload.getProposalHash().toBuffer().toString('hex');
proposal_response_payload.extension = decodeChaincodeAction(proto_proposal_response_payload.getExtension());
return proposal_response_payload;
}
function decodeChaincodeAction(action_bytes) {
var chaincode_action = {};
var proto_chaincode_action = _proposalProto.ChaincodeAction.decode(action_bytes);
chaincode_action.results = decodeReadWriteSets(proto_chaincode_action.getResults());
chaincode_action.events = decodeChaincodeEvents(proto_chaincode_action.getEvents());
chaincode_action.response = decodeResponse(proto_chaincode_action.getResponse());
chaincode_action.chaincode_id = decodeChaincodeID(proto_chaincode_action.getChaincodeId());
return chaincode_action;
}
function decodeReadWriteSets(rw_sets_bytes) {
var proto_tx_read_write_set = _rwsetProto.TxReadWriteSet.decode(rw_sets_bytes);
var tx_read_write_set = {};
tx_read_write_set.data_model = proto_tx_read_write_set.getDataModel();
if (proto_tx_read_write_set.getDataModel() === _rwsetProto.TxReadWriteSet.DataModel.KV) {
tx_read_write_set.ns_rwset = [];
let proto_ns_rwset = proto_tx_read_write_set.getNsRwset();
for (let i in proto_ns_rwset) {
let kv_rw_set = {};
let proto_kv_rw_set = proto_ns_rwset[i];
kv_rw_set.namespace = proto_kv_rw_set.getNamespace();
kv_rw_set.rwset = decodeKVRWSet(proto_kv_rw_set.getRwset());
tx_read_write_set.ns_rwset.push(kv_rw_set);
}
} else {
// not able to decode this type of rw set, return the array of byte[]
tx_read_write_set.ns_rwset = proto_tx_read_write_set.getNsRwset();
}
return tx_read_write_set;
}
function decodeKVRWSet(kv_bytes) {
var proto_kv_rw_set = _kv_rwsetProto.KVRWSet.decode(kv_bytes);
var kv_rw_set = {};
// KV readwrite set has three arrays
kv_rw_set.reads = [];
kv_rw_set.range_queries_info = [];
kv_rw_set.writes = [];
// build reads
let reads = kv_rw_set.reads;
var proto_reads = proto_kv_rw_set.getReads();
for (let i in proto_reads) {
reads.push(decodeKVRead(proto_reads[i]));
}
// build range_queries_info
let range_queries_info = kv_rw_set.range_queries_info;
var proto_range_queries_info = proto_kv_rw_set.getRangeQueriesInfo();
for (let i in proto_range_queries_info) {
range_queries_info.push(decodeRangeQueryInfo(proto_range_queries_info[i]));
}
// build writes
let writes = kv_rw_set.writes;
var proto_writes = proto_kv_rw_set.getWrites();
for (let i in proto_writes) {
writes.push(decodeKVWrite(proto_writes[i]));
}
return kv_rw_set;
}
function decodeKVRead(proto_kv_read) {
let kv_read = {};
kv_read.key = proto_kv_read.getKey();
let proto_version = proto_kv_read.getVersion();
if (proto_version) {
kv_read.version = {};
kv_read.version.block_num = proto_version.getBlockNum().toString();
kv_read.version.tx_num = proto_version.getTxNum().toString();
} else {
kv_read.version = null;
}
return kv_read;
}
function decodeRangeQueryInfo(proto_range_query_info) {
let range_query_info = {};
range_query_info.start_key = proto_range_query_info.getStartKey();
range_query_info.end_key = proto_range_query_info.getEndKey();
range_query_info.itr_exhausted = proto_range_query_info.getItrExhausted();
// reads_info is one of QueryReads
let proto_raw_reads = proto_range_query_info.getRawReads();
if (proto_raw_reads) {
range_query_info.raw_reads = {};
range_query_info.raw_reads.kv_reads = [];
for (let i in proto_raw_reads.kv_reads) {
let kv_read = decodeKVRead(proto_raw_reads.kv_reads[i]);
range_query_info.raw_reads.kv_reads.push(kv_read);
}
}
// or QueryReadsMerkleSummary
let proto_reads_merkle_hashes = proto_range_query_info.getReadsMerkleHashes();
if (proto_reads_merkle_hashes) {
range_query_info.reads_merkle_hashes = {};
range_query_info.reads_merkle_hashes.max_degree = proto_reads_merkle_hashes.getMaxDegree();
range_query_info.reads_merkle_hashes.max_level = proto_reads_merkle_hashes.getMaxLevel();
range_query_info.reads_merkle_hashes.max_level_hashes = proto_reads_merkle_hashes.getMaxLevelHashes();
}
return range_query_info;
}
function decodeKVWrite(proto_kv_write) {
let kv_write = {};
kv_write.key = proto_kv_write.getKey();
kv_write.is_delete = proto_kv_write.getIsDelete();
kv_write.value = proto_kv_write.getValue().toBuffer().toString();
return kv_write;
}
function decodeChaincodeEvents(event_bytes) {
var events = {};
var proto_events = _ccEventProto.ChaincodeEvent.decode(event_bytes);
events.chaincode_id = proto_events.getChaincodeId();
events.tx_id = proto_events.getTxId();
events.event_name = proto_events.getEventName();
events.payload = proto_events.getPayload().toBuffer();
return events;
}
function decodeResponse(proto_response) {
if (!proto_response) return null;
var response = {};
response.status = proto_response.getStatus();
response.message = proto_response.getMessage();
response.payload = proto_response.getPayload().toBuffer().toString();
return response;
}
function decodeChaincodeID(proto_chaincode_id) {
var chaincode_id = {};
if(!proto_chaincode_id) {
console.log('decodeChaincodeID - no proto_chaincode_id found');
return chaincode_id;
}
chaincode_id.path = proto_chaincode_id.getPath();
chaincode_id.name = proto_chaincode_id.getName();
chaincode_id.version = proto_chaincode_id.getVersion();
return chaincode_id;
}
As far as i know ProposalResponse Payload can be got from the TransactionActionInfo class and returns a byte[] array that can be decoded with a utility method .
void blockWalker(Channel channel) throws InvalidArgumentException, ProposalException, IOException {
try {
BlockchainInfo channelInfo = channel.queryBlockchainInfo();
for (long current = channelInfo.getHeight() - 1; current > -1; --current) {
BlockInfo returnedBlock = channel.queryBlockByNumber(current);
final long blockNumber = returnedBlock.getBlockNumber();
out("current block number %d has data hash: %s", blockNumber, Hex.encodeHexString(returnedBlock.getDataHash()));
out("current block number %d has previous hash id: %s", blockNumber, Hex.encodeHexString(returnedBlock.getPreviousHash()));
out("current block number %d has calculated block hash is %s", blockNumber, Hex.encodeHexString(SDKUtils.calculateBlockHash(blockNumber, returnedBlock.getPreviousHash(), returnedBlock.getDataHash())));
final int envelopCount = returnedBlock.getEnvelopCount();
assertEquals(1, envelopCount);
out("current block number %d has %d envelope count:", blockNumber, returnedBlock.getEnvelopCount());
int i = 0;
for (BlockInfo.EnvelopeInfo envelopeInfo : returnedBlock.getEnvelopeInfos()) {
++i;
out(" Transaction number %d has transaction id: %s", i, envelopeInfo.getTransactionID());
final String channelId = envelopeInfo.getChannelId();
out(" Transaction number %d has channel id: %s", i, channelId);
out(" Transaction number %d has epoch: %d", i, envelopeInfo.getEpoch());
out(" Transaction number %d has transaction timestamp: %tB %<te, %<tY %<tT %<Tp", i, envelopeInfo.getTimestamp());
out(" Transaction number %d has type id: %s", i, "" + envelopeInfo.getType());
if (envelopeInfo.getType() == TRANSACTION_ENVELOPE) {
BlockInfo.TransactionEnvelopeInfo transactionEnvelopeInfo = (BlockInfo.TransactionEnvelopeInfo) envelopeInfo;
out(" Transaction number %d has %d actions", i, transactionEnvelopeInfo.getTransactionActionInfoCount());
out(" Transaction number %d isValid %b", i, transactionEnvelopeInfo.isValid());
out(" Transaction number %d validation code %d", i, transactionEnvelopeInfo.getValidationCode());
int j = 0;
for (BlockInfo.TransactionEnvelopeInfo.TransactionActionInfo transactionActionInfo : transactionEnvelopeInfo.getTransactionActionInfos()) {
++j;
out(" Transaction action %d has response status %d", j, transactionActionInfo.getResponseStatus());
out(" Transaction action %d has response message bytes as string: %s", j,
printableString(new String(transactionActionInfo.getResponseMessageBytes(), "UTF-8")));
out(" Transaction action %d has %d endorsements", j, transactionActionInfo.getEndorsementsCount());
for (int n = 0; n < transactionActionInfo.getEndorsementsCount(); ++n) {
BlockInfo.EndorserInfo endorserInfo = transactionActionInfo.getEndorsementInfo(n);
out("Endorser %d signature: %s", n, Hex.encodeHexString(endorserInfo.getSignature()));
out("Endorser %d endorser: %s", n, new String(endorserInfo.getEndorser(), "UTF-8"));
}
out(" Transaction action %d has %d chaincode input arguments", j, transactionActionInfo.getChaincodeInputArgsCount());
for (int z = 0; z < transactionActionInfo.getChaincodeInputArgsCount(); ++z) {
out(" Transaction action %d has chaincode input argument %d is: %s", j, z,
printableString(new String(transactionActionInfo.getChaincodeInputArgs(z), "UTF-8")));
}
out(" Transaction action %d proposal response status: %d", j,
transactionActionInfo.getProposalResponseStatus());
out(" Transaction action %d proposal response payload: %s", j,
printableString(new String(transactionActionInfo.getProposalResponsePayload())));
TxReadWriteSetInfo rwsetInfo = transactionActionInfo.getTxReadWriteSet();
if (null != rwsetInfo) {
out(" Transaction action %d has %d name space read write sets", j, rwsetInfo.getNsRwsetCount());
for (TxReadWriteSetInfo.NsRwsetInfo nsRwsetInfo : rwsetInfo.getNsRwsetInfos()) {
final String namespace = nsRwsetInfo.getNaamespace();
KvRwset.KVRWSet rws = nsRwsetInfo.getRwset();
int rs = -1;
for (KvRwset.KVRead readList : rws.getReadsList()) {
rs++;
out(" Namespace %s read set %d key %s version [%d:%d]", namespace, rs, readList.getKey(),
readList.getVersion().getBlockNum(), readList.getVersion().getTxNum());
if ("bar".equals(channelId) && blockNumber == 2) {
if ("example_cc_go".equals(namespace)) {
if (rs == 0) {
assertEquals("a", readList.getKey());
assertEquals(1, readList.getVersion().getBlockNum());
assertEquals(0, readList.getVersion().getTxNum());
} else if (rs == 1) {
assertEquals("b", readList.getKey());
assertEquals(1, readList.getVersion().getBlockNum());
assertEquals(0, readList.getVersion().getTxNum());
} else {
fail(format("unexpected readset %d", rs));
}
TX_EXPECTED.remove("readset1");
}
}
}
rs = -1;
for (KvRwset.KVWrite writeList : rws.getWritesList()) {
rs++;
String valAsString = printableString(new String(writeList.getValue().toByteArray(), "UTF-8"));
out(" Namespace %s write set %d key %s has value '%s' ", namespace, rs,
writeList.getKey(),
valAsString);
if ("bar".equals(channelId) && blockNumber == 2) {
if (rs == 0) {
assertEquals("a", writeList.getKey());
assertEquals("400", valAsString);
} else if (rs == 1) {
assertEquals("b", writeList.getKey());
assertEquals("400", valAsString);
} else {
fail(format("unexpected writeset %d", rs));
}
TX_EXPECTED.remove("writeset1");
}
}
}
}
}
}
}
}
if (!TX_EXPECTED.isEmpty()) {
// fail(TX_EXPECTED.get(0));
}
} catch (InvalidProtocolBufferRuntimeException e) {
throw e.getCause();
}
}
The utility method printableString()
static String printableString(final String string) {
int maxLogStringLength = 10000;
if (string == null || string.length() == 0) {
return string;
}
String ret = string.replaceAll("[^\\p{Print}]", "\n");
ret = ret.substring(0, Math.min(ret.length(), maxLogStringLength)) + (ret.length() > maxLogStringLength ? "..." : "");
return ret;
}
I am trying to insert mail to Google Mailbox using GMail APIs.
I want to upload mails of size more than 5 mb. So that I am using Resumable upload request.
I have used POST request first to initiate a resumable upload which gives "200 OK" response.
Post Request:
String postUrl = "https://www.googleapis.com/upload/gmail/v1/users/" + "<username>" + "/messages/send?uploadType=resumable";
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(postUrl);
httpRequest.Headers["Authorization"] = "Bearer " + f_token;// AccessToken;
httpRequest.Headers["X-Upload-Content-Type"] = "message/rfc822";
httpRequest.Headers["X-Upload-Content-Length"] = f_bytes.Length.ToString();
httpRequest.Method = "POST";
httpRequest.ContentLength = 0;
var response = (HttpWebResponse)httpRequest.GetResponse(); // 200 OK
From that response I get location URL to upload EML.
Location: https://www.googleapis.com/upload/gmail/v1/users//messages/send?uploadType=resumable&upload_id=AEnB2UqeNYKVyyQdL07RZcbenWOqY8a2NFVIsQrbA-S-vxwUXC_W4ORQtpPx1HG6tc4Indx8AvqDjwXII3F6OW0G3wsdUMUjHw
To upload EML file I used Location URL as PUT URL to create request.
putUrl = https://www.googleapis.com/upload/gmail/v1/users/<username>/messages/send?uploadType=resumable&upload_id=AEnB2UqeNYKVyyQdL07RZcbenWOqY8a2NFVIsQrbA-S-vxwUXC_W4ORQtpPx1HG6tc4Indx8AvqDjwXII3F6OW0G3wsdUMUjHw";
HttpWebRequest httpRequest1 = (HttpWebRequest)WebRequest.Create(postUrl);
httpRequest1.Method = "PUT";
httpRequest1.ContentLength = f_bytes.Length;
int EndOffset = f_bytes.Length;//5120000;5242880
httpRequest1.Headers["Content-Range"] = "bytes " + 0 + "-" + EndOffset + "/" + f_bytes.Length;
httpRequest1.ContentType = "message/rfc822";
MemoryStream stream = new MemoryStream(f_bytes);
System.IO.Stream requestStream = httpRequest1.GetRequestStream();
{
stream.CopyTo(requestStream);
requestStream.Flush();
requestStream.Close();
}
HttpWebResponse f_webResponse = (HttpWebResponse)httpRequest1.GetResponse(); //Exception
Exception :
The remote server returned an error: (400) Bad Request.
Please suggest soluion to upload eml file in a particular folder of mailbox .
I am able to send mail using resumable upload.
if (f_MailService == null)
{
bool isCreated = createMailService(ref f_MailService);
}
FileStream fs = new FileStream(#p_EMLPath, FileMode.Open,FileAccess.Read);
Create HTTPRequest for sending mail :
string postUrl = "https://www.googleapis.com/upload/gmail/v1/users/ab#edu.cloudcodes.com/messages/send?uploadType=resumable";
HttpWebRequest f_httpRequest = (HttpWebRequest)WebRequest.Create(postUrl);
f_httpRequest.Headers["X-Upload-Content-Type"] = "message/rfc822";
f_httpRequest.Headers["X-Upload-Content-Length"] = fs.Length.ToString();
f_httpRequest.Headers["Authorization"] = "Bearer " + f_token;
f_httpRequest.Method = "POST";
//f_httpRequest.ContentLength = 524288;
f_httpRequest.ContentType = "application/json; charset=UTF-8";//"message/rfc822";
f_httpRequest.ContentLength = fs.Length;
f_httpRequest.Timeout = 6000000;
f_httpRequest.SendChunked = true;
Get Response for first POST request :
try
{
using (Stream f_ObjHttpStream = f_httpRequest.GetRequestStream())
{
}
}
catch (Exception EX)
{
}
try
{
using (var response = (HttpWebResponse)f_httpRequest.GetResponse())
{
// data = ReadResponse(response);
UploadUrl = response.Headers["Location"].ToString();
}
}
catch (WebException exception)
{
using (var response = (HttpWebResponse)exception.Response)
{
// data = ReadResponse(response);
}
}
Read EML File & send chunk data to upload
byte[] Arrbyte = new byte[1024];
int ReadByte = 0;
while (fs.Length > ReadByte)
{
bool ac = false;
int ByteRead = 0;
byte[] Data = new byte[4194304];
byte[] LastData;
//Read block of bytes from stream into the byte array
// if (ReadByte == 0)
{
ByteRead = fs.Read(Data, 0, Data.Length);
}
//else
{
if ((ReadByte + Data.Length) > fs.Length)
{
//fs.Length - ReadByte-
LastData = new byte[fs.Length - ReadByte];
ByteRead = fs.Read(LastData, 0, LastData.Length);
CallPUTReq(fs.Length, LastData);
ac = true;
}
}
//f_MsgRawStr = Convert.ToBase64String(f_bytes).TrimEnd(padding).Replace('+', '-').Replace('/', '_');
ReadByte = ReadByte + ByteRead;
if (ac == false)
{
CallPUTReq(fs.Length, Data);
}
//long pos = fs.Seek(0, SeekOrigin.Current );
//fs.Position = ReadByte;
}
private void CallPUTReq(long p_lenth, byte[] Arrbyte)
{
try
{
String postUrl = UploadUrl; //"https://www.googleapis.com/upload/gmail/v1/users/ab#edu.cloudcodes.com/messages/send?uploadType=resumable&upload_id=AEnB2UqZNtZVwWulAOhAVoFp-pZ-vTMcIXOpt_0dH_6jJecpm2Y1MNOGkE6JoDb0kn9Dt4yuHHMZWR--dBncxWQkZctF9h6jiPSL5uJDKeYE9Ut1c7-fImc";
int EndOffset = 0;
HttpWebRequest httpRequest1 = (HttpWebRequest)WebRequest.Create(postUrl);
httpRequest1.Method = "PUT";
httpRequest1.ContentLength = Arrbyte.Length;
if (rangeStartOffset == 0)
{
EndOffset = Arrbyte.Length - 1;
}
else
{
EndOffset = rangeStartOffset + Arrbyte.Length - 1;
if (EndOffset > p_lenth)
{
EndOffset = Convert.ToInt32(p_lenth);
httpRequest1.ContentLength = EndOffset - rangeStartOffset;
}
}//5120000;5242880
httpRequest1.Headers["Content-Range"] = "bytes " + rangeStartOffset + "-" + EndOffset + "/" + p_lenth; //"bytes */" + p_lenth; //
httpRequest1.ContentType = "message/rfc822";
httpRequest1.Timeout = 6000000;
UTF8Encoding encoding = new UTF8Encoding();
Stream stream = httpRequest1.GetRequestStream();
stream.Write(Arrbyte, 0, Arrbyte.Length);
stream.Close();
try
{
using (Stream f_ObjHttpStream = httpRequest1.GetRequestStream())
{
}
}
catch (Exception EX)
{
}
WebResponse response1 = null;
try
{
using (response1 = (HttpWebResponse)httpRequest1.GetResponse())
{
}
}
catch (Exception ex)
{
// UploadUrl = response1.Headers["Location"].ToString();
}
//4194303
rangeStartOffset = EndOffset +1;
}
catch (Exception)
{
}
}
i have created an application in J2ME that uses the following method to connect to a server. php is used on the Server side to process the requests. the application works fine on some phones like NOkia asha 303 but throws IOException on other phones what could be the problem with this code. this method is called on a different thread. i also want to ask if you use post in j2me and set the
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
do you have to urlencode the data before sending or that is handled automatically by j2me
public String sendData(String serverUrl, String dataToSend) {
String strResponse = "0"; //string to hold serverResponse
StringBuffer sb = new StringBuffer("");
HttpConnection httpConn = null;
InputStream inputStream = null;
OutputStream outStream = null;
try {
//convert the dataToSend to bytes
String strData = dataToSend; // get the data to Send and store it in a variable.
byte[] dataToSendBytes = strData.getBytes();
//open the Connection to the server.
httpConn = (HttpConnection) Connector.open(serverUrl, Connector.READ_WRITE, true);
if (httpConn != null) {
httpConn.setRequestMethod(HttpConnection.POST); // method used to send the data.
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.1");
//httpConn.setRequestProperty("Content-Language", "en-US"); //language to use.
//setRequestProperty("Connection", "close") ===> could generate or Solve IOExceptions on different mobile Phones.
//httpConn.setRequestProperty("Connection", "close");
//setting the Content-length could have issues with some Servers===>
//if the dataToSend is Empty String => contentLen = 0 , else get length of the dataBytes.
String contentLen = ((dataToSend.length() > 0) ? Integer.toString(dataToSendBytes.length) : Integer.toString(0));
//httpConn.setRequestProperty("Content-length", contentLen); //not working on Emulator ....enable on shipping application.
//open the output Stream to send data to the Server.
outStream = httpConn.openOutputStream();
// send the bytes of data to the Server.===>
//outStream.write(dataToSendBytes);
//send the data bytes to the Server.
int byteLen = dataToSendBytes.length; //length of byteToSend.
for (int k = 0; k < byteLen; k++) {
//send all the databytes to the Server.
outStream.write(dataToSendBytes[k]);
}
//close the outputStream ===immediately after sending the data bytes to the Server===>eliminates the IOExceptions.
closeOutStream(outStream);
//get response code on Sending Data===> getting response code automatically flushes the output data.
ntworkResponseCode = httpConn.getResponseCode();
if (ntworkResponseCode == HttpConnection.HTTP_OK) {
//connection to the Server was okay.
if (httpConn != null) {
//read the Response From the Server-----------
inputStream = httpConn.openInputStream(); // open the inputStream.
//get server Response Content length.
int contLen = (int) httpConn.getLength();
byte[] serverResponseBytes; //byte array to store the serverResponse.
if (contLen != -1) {
//store the serverResponse to a byte array.===> using a byte buffer could be faster.
serverResponseBytes = new byte[contLen];
inputStream.read(serverResponseBytes);
//convert the bytes to String and store them to the StringBuffer.
sb.append(new String(serverResponseBytes));
} else {
//serverResponse Length not available===> read character by character could be slower.
int read;
while ((read = inputStream.read()) != -1) {
sb.append((char) read);
}
}
//store the server response in a String.
strResponse = sb.toString();
}
} else {
//connection problem occured.
//throw new IOException("Http Response Code [" + ntworkResponseCode + "]");
}
}// the httpConnection Not null.--end.
} catch (IllegalArgumentException arge) {
strResponse = CONNECTION_EXCEPTION;
} catch (ConnectionNotFoundException cone) {
//a string to show we got an exception
strResponse = CONNECTION_EXCEPTION;
} catch (IOException ioe) {
//a string to show we got an exception
strResponse = CONNECTION_EXCEPTION;
} catch (SecurityException se) {
//user cancelled the Connection Request.
strResponse = CONNECTION_EXCEPTION;
} finally {
//close all the connection streams
try {
if (inputStream != null) {
//close the inputStream
inputStream.close();
inputStream = null;
}
if (outStream != null) {
//close the outStream.
outStream.close();
outStream = null;
}
if (httpConn != null) {
//close the connection object.
httpConn.close();
httpConn = null;
}
} catch (IOException ie) {
//show exception occured.
}
}
//return server Response to the Client.
return strResponse;
}
While I am uploading the mobile and application number in multipart from-data from mobile it is hitting the server and data is storing in database.Now I added captured image to it and sent to server it is showing an exception.
org.apache.commons.fileupload.FileUploadBase$UnknownSizeException: the request was rejected because its size is unknown
at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:305)
at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest (ServletFileUpload.java:116)
at org.apache.jsp.photo_jsp._jspService(photo_jsp.java:103)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:384)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:320)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:228)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:216)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process (Http11Protocol.java:634)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:445)
at java.lang.Thread.run(Unknown Source)
Here I am sending Mobile and application Number and captured image in bytes (imagecapturephoto1). Captured image is storing in view after taking photo.But when we are uploading it is showing exception.
try
{
System.out.println("url:" + serverUrl);
connection = (HttpConnection)Connector.open(serverUrl,Connector.READ_WRITE);
connection.setRequestMethod(HttpConnection.POST);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=*****");
connection.setRequestProperty("User-Agent", "Profile/MIDP-2.1 Configuration/CLDC-1.1");
connection.setRequestProperty("Accept", "application/octet-stream" );
writer = new DataOutputStream(connection.openDataOutputStream());
// writer =new DataOutputStream( conn.openOutputStream());
String name="applicationNumber", name1="mobileNumber",name3="photo",
mimeType="text/plain",mimeType2="image/jpeg";
String value="123456789", value1="9849765432",fileName="applicationphoto.jpeg";
// write boundary
writeString(PREFIX);
writeString(boundary);
writeString(NEWLINE);
// write content header
writeString("Content-Disposition: form-data; name=\"" + name + "\"");
writeString(NEWLINE);
if (mimeType != null)
{
writeString("Content-Type: " + mimeType);
writeString(NEWLINE);
}
writeString("Content-Length: " + applicationNumber.length());
writeString(NEWLINE);
writeString(NEWLINE);
// write content
writeString(applicationNumber);
writeString(NEWLINE);
// write boundary
writeString(PREFIX);
writeString(boundary);
writeString(NEWLINE);
// write content header
writeString("Content-Disposition: form-data; name=\"" + name1 + "\"");
writeString(NEWLINE);
if (mimeType != null)
{
writeString("Content-Type: " + mimeType);
writeString(NEWLINE);
}
writeString("Content-Length: " + mobileNumber.length());
writeString(NEWLINE);
writeString(NEWLINE);
// write content
writeString(mobileNumber);
writeString(NEWLINE);
//uploading image...........
// write boundary
writeString(PREFIX);
writeString(boundary);
writeString(NEWLINE);
// write content header
writeString("Content-Disposition: form-data; name=\"" + name3
+ "\"; filename=\"" + fileName + "\"");
writeString(NEWLINE);
if (mimeType2 != null)
{
writeString("Content-Type: " + mimeType2);
writeString(NEWLINE);
}
writeString("Content-Length: " + imagecapturephoto1.length);
writeString(NEWLINE);
writeString(NEWLINE);
// write content
// SEND THE IMAGE
int index = 0;
int size = 1024;
do
{
System.out.println("write:" + index);
if((index+size)<=imagecapturephoto1.length)
{
writer.write(imagecapturephoto1, index, size);
}
index+=size;
}while(index<imagecapturephoto1.length);
writeString(NEWLINE);
writeString(PREFIX);
writeString(boundary);
writeString(PREFIX);
writeString(NEWLINE);
writer.flush();
//writer.write("-- ***** -- \r\n".getBytes());
serverResponseMessage = connection.getResponseMessage();
InputStream inputstream = connection.openInputStream();
// retrieve the response from server
int chnumber;
StringBuffer sbuffer =new StringBuffer();
while( ( chnumber= inputstream.read() ) != -1 )
{
sbuffer.append( (char)chnumber );
}
String resonsestring=sbuffer.toString();
int end=resonsestring.length();
int tempstr=resonsestring.indexOf(">");
statusResponse=resonsestring.substring(tempstr+1, end);
statusResponse="SUCCESS";
//outputStream.close();
writer.close();
connection.close();
return serverResponseMessage;
}
catch (Exception ex)
{
//statusResponse="SUCCESS";
ex.printStackTrace();
return null;
}
Please suggest me,How we have to upload image from mobile.I was struck from last 10 days.please suggest me how to solve this issue.
Thanks in advance.
-Teja.
kindly try following code segment, Please ignore lat-lon coding.
private void postImageToServer(String curURL) throws Exception
{
// Open up a http connection with the Web server for both send and receive operations
midlet.get_frmLog().append("HttpConnection Enter");
httpConnection = (HttpConnection)Connector.open(URL, Connector.READ_WRITE);
// Set the request method to POST
httpConnection.setRequestMethod(HttpConnection.POST);
// Set the request headers
httpConnection.setRequestProperty(ConstantCodes.ACTION_MODE_PARAMETER,action);
httpConnection.setRequestProperty(ConstantCodes.USER_NAME_REQUEST_PARAMETER,userName);
//httpConnection.setRequestProperty("lat","22.955804");
//httpConnection.setRequestProperty("lon","72.685876");
//httpConnection.setRequestProperty("lat",LatLonFetcherThread.getLatitude());
//httpConnection.setRequestProperty("lon",LatLonFetcherThread.getLongitude());
/*lat = "23.0172";
lon = "72.3416";*/
if ( midlet.get_choiceGroupGPS().getSelectedIndex() == 0 )
{
lat = LatLonFetcherThread.getLatitude();
lon = LatLonFetcherThread.getLongitude();
}
else if ( midlet.get_choiceGroupGPS().getSelectedIndex() != 0 ) // Added By KALPEN
{
if ( midlet.state == mREPORTER.STATE_READING )
{
double xLat,xLon;
try
{
GpsBt.instance().start();
//while (true)
{
gpsBt = GpsBt.instance();
if ( gpsBt.isConnected() )
{
location = gpsBt.getLocation();
//lat = location.utc;
//lon = location.utc;
lat = (location.latitude + location.northHemi);
lon = (location.longitude + location.eastHemi);
lat = lat.substring(0,lat.length()-1);
lon = lon.substring(0,lon.length()-1);
xLat = Double.parseDouble(lat) / (double)100.00;
xLon = Double.parseDouble(lon) / (double)100.00;
lat = xLat + "";
lon = xLon + "";
lat = lat.substring(0,7);
lon = lon.substring(0,7);
//lat = "23.0172";
//lon = "72.3416";
}
Thread.sleep(100);
}
}
catch ( Exception e ) { lat = "23.0172"; lon = "72.3416"; }
}
}
httpConnection.setRequestProperty("lat",lat); // Modifed by KALPEN
httpConnection.setRequestProperty("lon",lon); // Modifed by KALPEN
//String latlongStr = "Latitude: " + LatLonFetcherThread.getLatitude()
// + "\nLongitude: " + LatLonFetcherThread.getLongitude();
/*String latlongStr = "lat: 22.955804" + "lon: 72.685876";*/
//#style screenAlert
/*Alert latlonAlert = new Alert("LatLon alert" );
latlonAlert.setString(latlongStr);
mREPORTER.display.setCurrent(latlonAlert);*/
if(eventName == null || eventName.equals(""))
eventName = "default";
// all the headers are sending now and connection channel is establising
httpConnection.setRequestProperty(ConstantCodes.EVENT_NAME_REQUEST_PARAMETER, eventName);
httpConnection.setRequestProperty(ConstantCodes.CAMERAID_REQUEST_PARAMETER, cameraID);
httpConnection.setRequestProperty(ConstantCodes.COMPRESSION_MODE_REQUEST_PARAMETER, compressionMode);
midlet.get_frmLog().append("Write on server-->"+imageBytes.length);
DataOutputStream dos = httpConnection.openDataOutputStream();
dos.write(imageBytes);
midlet.threadFlag=true;
}
Above Method works fine with my code, as I am also trying to upload Image to Server.